异步/等待-代码在完成承诺之前执行

时间:2020-03-08 11:09:09

标签: javascript node.js promise async-await

我有一个异步函数来处理一个数组,并通过增加每个元素的时间间隔来调用另一个异步函数。

我等待所有诺言解决,然后将结果数组保存在文件中。尽管由于某些原因,写入文件操作会在解决承诺之前执行。 有人可以告诉我我可能做错了什么吗?

使用节点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);
  }
})();

1 个答案:

答案 0 :(得分:0)

这里的问题是这一行:

 setTimeout(async () => {

您执行setTimeout调用。这将安排回调在以后被调用。但是,您不必等待回调发生。而是使用一些承诺的setTimeout版本:

  const timer = ms => new Promise(res => setTimeout(res, ms));

那么您可以

  await timer(2000);
  await /*other stuff*/;
相关问题