【问题标题】:Async/Await - code executes before promise is resolved [duplicate]异步/等待 - 在解决承诺之前执行代码 [重复]
【发布时间】: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


【解决方案1】:

这里的问题是这一行:

 setTimeout(async () => {

你做了一个 setTimeout 调用。这将安排稍后调用回调。但是您不必等待回调发生。而是使用一些承诺版本的 setTimeout:

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

那么你就可以了

  await timer(2000);
  await /*other stuff*/;

【讨论】:

  • 谢谢,这解决了问题...由于某种原因,结果数组为空,但至少执行是正确的。
  • 啊,找到了。当然我错过了return语句:)
猜你喜欢
  • 2018-04-17
  • 1970-01-01
  • 2020-08-28
  • 2021-11-09
  • 1970-01-01
  • 2018-09-02
  • 2018-12-14
  • 2019-09-29
  • 2021-12-26
相关资源
最近更新 更多