1
我想处理一个项目的数组,并需要使用该块内的异步函数。我需要在外循环中使用async
函数,因此我可以在循环中使用await
。我该如何使用await和forEach?
但我似乎无法让循环“等待”,然后再继续。 下面的代码仅打印出msgs
作为[]
,然后运行循环。
// with a foreach
let msgs = [];
items.forEach(function(item, index) {
item.laws.forEach(async function(law) {
let orig = await Laws.coll.findOne({url: law.cname});
let title = Laws.title(orig);
let msg = `<${law.cname}|${title}>`;
msgs.push(msg);
debug("title", title, msg);
});
});
debug("msgs", msgs); // => shows []
,我也尝试过各种语法与map
items.map(await async function(item) {
item.laws.map(await async function(law) {
let orig = await Laws.coll.findOne({url: law.cname});
let title = Laws.title(orig);
let msg = `<${law.cname}|${title}>`;
msgs.push(msg);
debug("title", title, msg);
});
});
FWIW我想:
await item.laws.map(async function() ...
//and
item.laws.map(await async function() ...
没有成功。
在这两种情况下,循环运行后debug("msgs", msgs)
已打印。
感谢您的支持!我现在有另一个工具用于等待:) – dcsan