【发布时间】:2020-06-20 12:50:30
【问题描述】:
我有一个异步函数,它处理一个数组并通过增加每个元素的时间间隔来调用另一个异步函数。
我等待所有承诺解决,然后将结果数组保存在一个文件中。尽管由于某些原因,写入文件操作在 Promise 解决之前执行。 谁能告诉我我可能做错了什么?
使用node util将读写文件功能变成promise,getGuidesList返回promise。
(async () => {
try {
const file = await readFilePromise('./kommuner.json');
const municipalities = JSON.parse(file).municipalities;
console.log(municipalities);
const municipalities_new = await Promise.all(municipalities.map(async (municipality, index) => {
setTimeout(async () => {
let guides = await getGuidesList(municipality.municipality_id);
// const guides = [];
if (typeof guides === 'string') {
guides = [];
}
console.log(`Number of guides for ${municipality.municipality_name}: ${guides.length}`);
Reflect.set(municipality, 'guides_number', guides.length);
Reflect.set(municipality, 'guides', guides);
console.log(municipality)
}, index * 5000);
}))
console.log(municipalities_new);
await writeFilePromise('./kommuner_guide.json', JSON.stringify({
"municipalities": municipalities_new
}));
} catch (err) {
console.log(err);
}
})();
【问题讨论】:
-
我以前看过这段代码,就像一个小时前...它关闭了一个有用答案的链接...问题是,没有办法等待 setTimeout,所以不等待 setTimeout 里面的代码
-
setTimeout(async () => {})内部的await不是外部承诺链的一部分 -
谢谢。我用下面的答案解决了我的问题。
标签: javascript node.js promise async-await