[JS] cancellable async function loop
// cancellable async function loop
const asyncFunction = () => new Promise(resolve => {
console.log('loop');
setTimeout(resolve, 1000);
});
// 1
const asyncLoop1 = () => {
let loop = true;
const handler = () => {
loop && asyncFunction().then(handler);
};
handler();
return () => loop = false;
};
const cancel1 = asyncLoop1(); // start
cancel1(); // cancel
// 2
const asyncLoop2 = (flag = {loop: true}) => {
asyncFunction().then(() => flag.loop && asyncLoop2(flag));
return () => flag.loop = false;
};
const cancel2 = asyncLoop2(); // start
cancel2(); // cancel
// 3
async function asyncLoop3(signal) {
let loop = true;
signal.then(() => loop = false);
while(loop) {
await asyncFunction();
}
}
let cancel3;
const signal = new Promise(resolve => cancel3 = resolve);
asyncLoop3(signal); // start
cancel3(); // cancel
// 4
const asyncLoop4 = () => {
let loop = true;
const iterator = generator();
iterator.next();
function* generator() {
while(loop) {
asyncFunction().then(() => iterator.next());
yield;
}
}
return () => loop = false;
};
const cancel4 = asyncLoop4(); // start
cancel4(); // cancel