[英]setTimeout on promises inside a for loop
我想做的是这样的:
循环数据集合,为每个数据元素调用 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!");
}
所有的应许依旧一串串没有停顿。 我认为我对 Promises 的理解不足以调试这个......按照我想要的方式工作的代码是什么?
在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!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.