[英]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.