Javascript Cancel Async For Loop
I found this code in a project: const fn = async () => { let x = 0; for(let i = 0; i < 50; i++){ const res = await api.call(i); if(res.someProp) x++;
Solution 1:
This should do:
let token;
const fn = async () => {
const my = token = Symbol();
let x = 0;
for(let i = 0; i < 50 && my == token; i++){
const res = await api.call(i);
if(res.someProp) x++;
}
return x;
}
While there still can be some overlap between the calls, any previous loops will break their iteration as soon as the next fn()
call is started.
Solution 2:
You can use any technique of using an external flag variable to break the loop.
As a workaround you can try to use a custom Promise class (Live demo):
import CPromise from"c-promise2";
constdelay = ms => newPromise(resolve =>setTimeout(resolve, ms));
asyncfunctionapi(i) {
console.log(`Async API call [${i}]`);
awaitdelay(100);
return {};
}
constfn = () =>
CPromise.from(function* () {
let x = 0;
for (let i = 0; i < 50; i++) {
const res = yield api.call(i);
if (res.someProp) x++;
}
return x;
});
const cancelablePromise = fn().then(
() =>console.log("Done"),
(err) =>console.log(`Fail: ${err}`) // Fail: CanceledError: canceled
);
setTimeout(() => {
cancelablePromise.cancel(); // abort the async sequence (loop) after 3500ms
}, 3500);
Post a Comment for "Javascript Cancel Async For Loop"