Him*_*ati 3 javascript node.js reactjs es6-promise angular
当我在 nodejs 中创建我的 api 并尝试将 mongoose 返回计数推送到新创建的数组时,它不会等待 forEach 并执行 json.res() 并给出空响应。当我使用 setTimeout() 时,它会给出正确的结果。
let newcategories = [];
let service = 0;
const categories = await Category.find({}, '_id name');
categories.forEach(async (category) => {
service = await Service.count({category: category});
newcategories.push({ count:service });
console.log('newcategories is -- ', newcategories);
}); /* while executing this forEach it's not wait and execute res.json..*/
console.log('result --- ',result);
console.log('out newcategories is -- ', newcategories);
res.json({status: 200, data: newcategories});
Run Code Online (Sandbox Code Playgroud)
因此,您遇到的问题是,async标记的函数将默认返回一个承诺,但该Array.prototype.forEach方法并不关心回调函数的结果类型,它只是执行一个操作。
在你的async函数中,它会正确地await回答你的问题并填充你的新类别,但forEach类别上的循环将早已消失。
您可以选择将语句转换为for .. of循环,也可以使用mapand thenawait Promise.all( mapped )
for..of 循环就像这样
for (let category of categories) {
service = await Service.count({category: category});
newcategories.push({ count:service });
console.log('newcategories is -- ', newcategories);
}
Run Code Online (Sandbox Code Playgroud)
地图版本看起来像这样
await Promise.all( categories.map(async (category) => {
service = await Service.count({category: category});
newcategories.push({ count:service });
console.log('newcategories is -- ', newcategories);
}));
Run Code Online (Sandbox Code Playgroud)
第二个版本可以正常工作,因为Promise.all仅在所有 Promise 完成后才会解析,并且映射将为每个类别返回一个可能未解析的 Promise
您需要使用 map 而不是 forEach 来收集等待并等待它们完成。编辑:或者你可以使用for..of它非常整洁(感谢其他人)!
const categories = ['a', 'b', 'c'];
function getNextCategory(oldCategory) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(String.fromCharCode(oldCategory.charCodeAt(0)+1));
}, 1000);
});
}
async function blah() {
const categoryPromises = categories.map(getNextCategory);
const nextCategories = await Promise.all(categoryPromises);
console.log(nextCategories);
}
blah();
async function blah2() {
const nextCategories = [];
for (const category of categories) {
nextCategories.push(await getNextCategory(category));
};
console.log(nextCategories);
}
blah2();Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2482 次 |
| 最近记录: |