let cancelled = false;
task(promise => cancelled ? new Promise(() => {}) : promise);
return { cancel() { cancelled = true; } };
}
async function main() {
let execution = start(async check => {
let x = 0;
while (true) {
await check(sleep(1000));
console.log(++x);
}
});
await sleep(5000);
execution.cancel();
}
Updated helper to be nestable: function start(task, isOuterCancelled = null) { let cancelled = false; function isCancelled() { return isOuterCancelled?.() || cancelled; } function nestedStart(task) { start(task, isCancelled); } function check(promise) { if (isCancelled()) { return new Promise(() => {}); } return promise; } return { promise: task(check, nestedStart), cancel() { cancelled = true; }, }; }
Обсуждают сегодня