[英]How to use async await inside another async function
i have a question about using async await inside another promise.我有一个关于在另一个 promise 中使用异步等待的问题。 I have a function call another function to get a transaction details.我有一个 function 调用另一个 function 以获取交易详细信息。
When i running the function LastTransactions the field details do not show results.当我运行 function LastTransactions 时,字段详细信息不显示结果。 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和一个细节 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;
}
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.您需要使用Promise.all
方法来获取一组承诺,并在每个单独的交易详情调用完成后返回一个包含您的交易的数组。
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:参考:
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.由于transactionDetails(item.transaction_id)
是异步的,因此您也需要等待它,否则它将立即返回,并且 trxDetails 将包含 promise object,而不是 response.data。
try this:尝试这个:
transactions = response.data.map(async (item) => {
return {
id : item.id,
transactionId : item.transaction_id,
trxDetails : [await transactionDetails(item.transaction_id)],
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.