[英]How to return data from nested async function
async getSettlementByUser(email): Promise<any> {
let listofTerminalId = [];
// Get current user
let user = await this.userModel.findOne({ email: email });
// get list of sn
let tpeIndexes = user.bindedSn.map((item) => item);
//list des tpes binded to current user
let tpe = tpeIndexes.map(async (index) => {
let list = await this.tpeModel.find({ sn: index });
// console.log('liste des tpes', list);
let terminalId = list.map((item) => item.terminalId);
// console.log('terminalId', ...terminalId);
listofTerminalId.push(...terminalId);
console.log('listofTerminalId', listofTerminalId);
return await listofTerminalId.map(async (item) => {
return await this.modelSettlement
.find({ terminalID: item })
.then((res) => res)
.catch((err) => console.log(err));
});
// console.log('settlement', settlement);
// return settlement;
});
let promiseValue = await Promise.all(tpe);
console.log('promiseValue', promiseValue);
// // return promiseValue;
// return tpe;
}
OUTPUT
promiseValue [ [ Promise { <pending> } ], [ Promise { <pending> }, Promise { <pending> } ], [
Promise { <pending> },
Promise { <pending> },
Promise { <pending> } ] ]
我使用 Promise.all() 來處理這個嵌套異步仍然得到這個結果所以我該如何解決這個問題以及為什么它顯示這個錯誤
您只在嵌套的外層使用Promise.all
,而不是在 promise 的內部數組上使用。 你還需要做
return Promise.all(listofTerminalId.map(async (item) => {
// ^^^^^^^^^^^
return this.modelSettlement
.find({ terminalID: item })
.catch((err) => console.log(err));
}));
但是,鑒於listofTerminalId.push(...terminalId)
,看起來您實際上不想要任何嵌套。 你可能只想
async getSettlementByUser(email): Promise<any> {
// Get current user
const user = await this.userModel.findOne({ email: email });
// list des tpes binded to current user
const tpes = await Promise.all(user.bindedSn.map(async (index) => {
const list = await this.tpeModel.find({ sn: index });
// console.log('liste des tpes', list);
return list.map((item) => item.terminalId);
}));
const listofTerminalId = tpes.flat();
console.log('listofTerminalId', listofTerminalId);
const settlements = await Promise.all(listofTerminalId.map((item) => {
return this.modelSettlement.find({ terminalID: item })
}));
console.log('settlements', settlements);
}
您需要將一系列承諾傳遞給Promise.all
方法,這意味着在將它們傳遞給.then
之前,您既不應該await
承諾也不應該等待Promise.all
。
所以它可能看起來像這樣:
async getSettlementByUser(email): Promise<any> {
let listofTerminalId = [];
let user = await this.userModel.findOne({ email: email });
let tpeIndexes = user.bindedSn.map((item) => item);
let tpe = tpeIndexes.map(async (index) => {
let list = await this.tpeModel.find({ sn: index });
let terminalId = list.map((item) => item.terminalId);
listofTerminalId.push(...terminalId);
return listofTerminalId.map((item) => {
return this.modelSettlement
.find({ terminalID: item })
});
});
let promiseValue = await Promise.all(tpe)
console.log('promiseValue', promiseValue);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.