【问题标题】:setTimeout on promises inside a for loopsetTimeout 在 for 循环中的 Promise
【发布时间】:2019-08-21 14:17:40
【问题描述】:

我想做的是这样的:

循环遍历数据集合,为每个数据元素调用 API,等待 promise 失败或解决,暂停 30 秒...然后对下一个数据元素再次执行此操作,直到没有可迭代的内容在集合中...最后显示“完成”消息。

到目前为止,这是我编写的代码,在其他 SO 问题中收集想法,这不是我想要的方式。

populateDB();

// these 2 helper functions were found on SO

function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function sleep(fn, ...args) {
  await timeout(30000);
  return fn(...args);
}

// this is the main function that makes the api calls
function populateDB() {

  for (let stock of universe.universe) {
    sleep(() => {
      // actual API call
      return alpha.data
        .daily(stock)
        .then(data => {
          // write data to the db when promise resolves
          db.get("stocks")
            .push({ [stock]: polishData(data) })
            .write();
        })
        .catch(err => console.log(err));
    });
  }

  console.log("Done!");
}

所有的承诺仍然一个接一个地链接,没有停顿。我认为我对 Promises 的理解不足以调试它...按照我希望的方式工作的代码是什么?

【问题讨论】:

  • async function populateDB 和 await sleep(() => {
  • 非常感谢@JaromandaX。要写答案吗?

标签: javascript arrays object ecmascript-6 promise


【解决方案1】:

在您的 populateDB 函数中使用 async/await:

async function populateDB() {

  for (let stock of universe.universe) {
    await sleep(() => {
      // actual API call
      return alpha.data
        .daily(stock)
        .then(data => {
          // write data to the db when promise resolves
          db.get("stocks")
            .push({ [stock]: polishData(data) })
            .write();
        })
        .catch(err => console.log(err));
    });
  }
  console.log("Done!");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2016-08-30
    • 2022-10-16
    • 1970-01-01
    相关资源
    最近更新 更多