node.jsaxiosendpoint

How should I call two endpoints when one depends on the other one?


I am currently learning web dev and I've come into this issue that it's probably a really common thing to do but I'm not really sure how to handle. I'm doing a process where I have to call two external endpoints were the second one depends on the response of the first one.

See, my first endpoint call gives me an ID that I need to use for my second endpoint call. Right now I've taken this approach:

export const inmediateDebit = async (
  amount) => {
  try {
    const debit = await axios.post("EXTERNAL ENDPOINT URL", {
      amount: amount
    });
    console.log('first API response:', debit.data);

    if (!debit.error) {
      const transactionId = debit.data.id
      console.log(transactionId)
      try {
        const debitCheck = await axios.get(`EXTERNAL ENDPOINT URL/${transactionId}`, {});
        console.log('second API response: ', debitCheck.data)
      } catch (error) {
        console.error("Operation Status Check API Error: ", error.response?.data || error.message)
      }
    }

    return debit.data;
  } catch (error) {
    console.error("Inmediate Debit API Error: ", error.response?.data || error.message);
    throw error;
  }
}

However, when entering the if !debit.error statement, debit.data is still undefined (correct me if I'm wrong, I understand it comes from happening as soon as the call is made and not waiting for the response?), so of course I get a wrong response from the second endpoint. I've thought about using a while loop that waits for the data of the first endpoint so I can call the second one, however, I've decided to ask here if this is a correct approach, calling one endpoint inside the other, or if I should instead make two separate endpoint calls and call them separate. I appreciate any help you guys can give me!


Solution

  • the await you're using should already make it so that it waits till you get a valid response.

    if there is an error, it's auto caught with the try-catch so !debit.error is unnecessary.

    not only is it unnecessary, when you get a successful response, the response won't have an error object. which means, even if you do get a successful response, you're skipping over it.

    just use await, the catch auto handles errors for both POST and GET in your case.

    export const inmediateDebit = async (amount) => {
      try {
        const debit = await axios.post("EXTERNAL ENDPOINT URL", {
          amount: amount
        });  
    
        const transactionId = debit.data.id;  
    
        const debitCheck = await axios.get(`EXTERNAL ENDPOINT URL/${transactionId}`);  
    
        return debitCheck.data;
        
      } catch (error) {
        // This will catch errors from both the POST and GET requests
        console.error("API Error: ", error.response?.data || error.message);
        throw error;
      }
    }