set在 for 循环内的承诺超时



我想做的是:

循环访问数据集合,为每个数据元素调用一个 API,等待承诺失败或解析,暂停 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!");
}

所有承诺的还在一个接一个地链子上,没有停顿。我认为我不够了解承诺来调试这个......按照我想要的方式工作的代码是什么?

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!");
}

最新更新