我有一个关于在另一个promise中使用异步等待的问题。我有一个函数调用另一个函数来获取交易明细。
当我运行LastTransactions函数时,字段详细信息不显示结果。有人可以帮助我吗?
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;
},
和详细功能
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;
}
答案 0 :(得分:1)
您需要利用Promise.all
方法获取一个promise数组,并在每次对交易细节的单独调用完成后返回一个包含交易的数组。
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;
};
参考:
答案 1 :(得分:0)
由于transactionDetails(item.transaction_id)
是异步的,因此您也需要等待它,否则它将立即返回,并且trxDetails将包含一个Promise对象,而不是response.data。
尝试一下:
transactions = response.data.map(async (item) => {
return {
id : item.id,
transactionId : item.transaction_id,
trxDetails : [await transactionDetails(item.transaction_id)],
}
});