Jaccon
Jaccon

Reputation: 79

How to use async await inside another async function

i have a question about using async await inside another promise. I have a function call another function to get a transaction details.

When i running the function LastTransactions the field details do not show results. Anyone can help me ?

LastTransactions: async (transactionKey, page) => {

    const api = `https://api.pagar.me/1/payables?recipient_id=${transactionKey}&count=${totalResults}&page=${page}&api_key=${PagarmeApiKey}`;
    const response = await axios.get(api);

    transactions = response.data.map((item) => {

      return {
        id : item.id,
        transactionId : item.transaction_id,
        trxDetails : [transactionDetails(item.transaction_id)],
      }

    });

    return transactions;

  },

and a detail function

async function transactionDetails(id){
    const response = await axios.get(`https://api.pagar.me/1/transactions/${id}?api_key=${PagarmeApiKey}`)
    const data = response.data;
    return data;
}

Upvotes: 6

Views: 17018

Answers (2)

goto
goto

Reputation: 4425

You need to utilize the Promise.all method to take an array of promises and return an array with your transactions once each individual call for transaction details finishes.

async (transactionKey, page) => {
  const api = 
    `https://api.pagar.me/1/payables?recipient_id=${transactionKey}&count=${totalResults}&page=${page}&api_key=${PagarmeApiKey}`;
  const response = await axios.get(api);
  
  // create an array of promises and wait for
  // all of them to resolve before continuing
  const transactions = await Promise.all(
    response.data.map(async item => {
      const { id, transaction_id } = item;

      // get transaction details for each item in the array
      const trxDetails = await transactionDetails(transaction_id);

      return {
        id,
        trxDetails,
        transactionId: transaction_id,
      };
    })
  );
  return transactions;
};

References:

Upvotes: 7

St.Nicholas
St.Nicholas

Reputation: 104

Since transactionDetails(item.transaction_id) is Asynchronous, you need to await that as well, otherwise it will return immediately and trxDetails will contain a promise object, and not response.data.

try this:

transactions = response.data.map(async (item) => {

      return {
        id : item.id,
        transactionId : item.transaction_id,
        trxDetails : [await transactionDetails(item.transaction_id)],
      }

    });

Upvotes: 0

Related Questions