[英]Async method returning undefined
我正在嘗試進行異步調用以返回結果。 結果是成功的,但無論我如何嘗試 - 調用者一直看到未定義。 你能幫我看看我做錯了什么。
Çaller:(總是不確定)
groups.forEach(async group =>{
let foundShares = await group.getShares();
console.log("found shares ", foundShares)
目標:(從我的日志中推送和填充 returnShares)
UserTaskGroupsSchema.methods.getShares = async function () {
console.log("start hasshares")
let returnShares = [];
let users = this._team.users;
users.forEach( user=>{
if (user.shares)
{
user.shares.forEach( share=>{
if (share.groupId.toString() === this._id.toString()){
console.log("found share with groupid ")
returnShares.push(share);
}
});
}
console.log("Returning returnshares ", returnShares)
return returnShares;
})
}```
看看這篇文章,看看為什么 forEach 中的 await 不起作用。 https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
將 forEach 替換為:
for (const group of groups) {
let foundShares = await group.getShares();
console.log("found shares ", foundShares)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.