Dictionary 如何将wait与map和forEach一起使用?
我试图处理一个项目数组,需要在块中使用异步函数。我需要使外循环成为某种类型的Dictionary 如何将wait与map和forEach一起使用?,dictionary,asynchronous,typescript,async-await,Dictionary,Asynchronous,Typescript,Async Await,我试图处理一个项目数组,需要在块中使用异步函数。我需要使外循环成为某种类型的async函数,以便在循环中使用wait // with a foreach let msgs = []; items.forEach(function(item, index) { item.laws.forEach(async function(law) { let orig = await Laws.coll.findOne({url: law.cnam
async
函数,以便在循环中使用wait
// 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 []
但我似乎无法在继续之前完成“等待”循环。
下面的代码只是将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 []
FWIW我试过:
await item.laws.map(async function() ...
//and
item.laws.map(await async function() ...
没有成功
在这两种情况下,循环都在
调试(“msgs”,msgs)
打印后运行。有两种方法可以解决此问题
代替(让项目){…}
原因是map和forEach都调用提供的回调,但不要等待它执行。谢谢!我现在有另一个工具可用于wait:)