[英]Set different intervals to call a specific asynchronous function
我想為接下來的 5 秒、10 秒、20 秒、40 秒、80 秒、160 秒和最后 8 分鍾調用一個異步函數getDetail()
。 在最后 8 分鍾,我希望它重定向到狀態頁面(成功或失敗頁面取決於我從 API 返回的響應)。
但是,在最后 8 分鍾內我無法讓它們正確,因為它會首先使用 for 循環觸發所有setTimeout
,然后一旦 for 循環命中i = 7
,它將直接將用戶重定向到 STATUS 頁面。
任何人都可以對此提出建議嗎? 如何更好地實現我想要的?
const pollingSecs = [5, 15, 35, 75, 155, 315, 480]
for (let i = 0; i < pollingSecs.length; i++) {
const timer = setTimeout(async () => {
const { success, data } = await getDetail()
if (success) {
// // redirect to STATUS page
}
}, pollingSecs[i] * 1000)
if (i === pollingSecs.length - 1) { // at the last 8 minutes
clearTimeout(timer)
// redirect to STATUS page
}
}
也許嘗試這樣的事情:
const pollingSecs = [5, 15, 35, 75, 155, 315, 480]
for (let i = 0; i < pollingSecs.length; i++) {
setTimeout(async () => {
const { success, data } = await getDetail()
if (success) {
// // redirect to STATUS page
}
if (i === pollingSecs.length - 1) { // at the last 8 minutes
// redirect to failure page
// redirect to STATUS page
}
}, pollingSecs[i] * 1000)
}
我會用 Promise 替換setTimeout
:
let sleep = n => new Promise(r => setTimeout(r, n));
const pollingSecs = [5, 15, 35, 75, 155, 315, 480]
for (let secs of pollingSecs) {
await sleep(secs * 1000);
const {success, data} = await getDetail();
if (success) {
// success!
return;
}
}
// failed!
我的答案基於@gog,除了它使用Promise.any
var timings = [5, 15, 35, 75, 155, 315, 480].map(n=>n*1000)
var promiseList = timings.map(t=>
new Promise((resolve,reject)=> {
setTimeout(async()=> {
const { success, data } = await getDetail();
if(success) {
resolve(data)
} else {
reject(data);
}
}, t);
})
);
Promise.any(promiseList).then((data)=>{ // any 1 is successful
// Redirect to success page
}).catch((data)=> { // all fail
// Redirect to failure page
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.