Eşzamansız bir prosedürü iptal etmek, özellikle derin iptal ve akış kontrolüne ihtiyaç duyduğunuzda hala önemsiz bir görev değildir. Şu anda yerel bir çözüm yok. Doğal olarak yapabileceğiniz her şey:
- iptal edilebilir hale getirmek istediğiniz her iç içe geçmiş async işlevine AbortController örneğini iletin
- tüm dahili mikro görevleri (istekler, zamanlayıcılar, vb.) sinyale abone olun
- isteğe bağlı olarak tamamlanan mikro görevleri sinyalden iptal etme
- çağrı
abort
abone olunan tüm mikro görevleri iptal etmek için denetleyicinin yöntemi
Bu oldukça ayrıntılı ve olası bellek sızıntıları ile zor bir çözümdür.
Bu zorluğa kendi çözümümü önerebilirim - c-promise2, iptal edilebilir sözler ve ECMA asenkron fonksiyonlar üreteçleri için iptal edilebilir bir alternatif sunar.
İşte temel bir örnek (Canlı Demo):
import { CPromise } from "c-promise2";
// deeply cancelable generator-based asynchronous function
const oneHourLastingFunction = CPromise.promisify(function* () {
// optionally just for logging
this.onCancel(() =>
console.log("oneHourLastingFunction::Cancel signal received")
);
yield CPromise.delay(5000); // this task will be cancelled on external timeout
return "myData";
});
async function nativeAsyncFn() {
await CPromise.delay(5000);
}
async function myFunc() {
let response;
try {
response = await oneHourLastingFunction().timeout(2000);
} catch (err) {
if (!CPromise.isCanceledError(err)) throw err;
console.warn("oneHourLastingFunction::timeout", err.code); // 'E_REASON_TIMEOUT'
}
await nativeAsyncFn(response);
}
const nativePromise = myFunc();
Derinden iptal edilebilir çözüm (tüm işlevler iptal edilebilir) (Canlı Demo):
import { CPromise } from "c-promise2";
// deeply cancelable generator-based asynchronous function
const oneHourLastingFunction = CPromise.promisify(function* () {
yield CPromise.delay(5000);
return "myData";
});
const otherAsyncFn = CPromise.promisify(function* () {
yield CPromise.delay(5000);
});
const myFunc = CPromise.promisify(function* () {
let response;
try {
response = yield oneHourLastingFunction().timeout(2000);
} catch (err) {
if (err.code !== "E_REASON_TIMEOUT") throw err;
console.log("oneHourLastingFunction::timeout");
}
yield otherAsyncFn(response);
});
const cancellablePromise = myFunc().then(
(result) => console.log(`Done: ${result}`),
(err) => console.warn(`Failed: ${err}`)
);
setTimeout(() => {
console.log("send external cancel signal");
cancellablePromise.cancel();
}, 4000);