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