रद्द एक अतुल्यकालिक प्रक्रिया अभी भी एक तुच्छ काम नहीं है, खासकर जब आप की जरूरत है गहरा रद्द करने और प्रवाह नियंत्रण. वहाँ कोई मूल समाधान । सभी आप कर सकते हैं natively:
- पास AbortController उदाहरण के लिए प्रत्येक नेस्टेड async समारोह में आप चाहते हैं बनाने के लिए रद्द
- सदस्यता सभी आंतरिक सूक्ष्म कार्य (अनुरोध, टाइमर, आदि) के लिए सिग्नल
- वैकल्पिक रूप से सदस्यता समाप्त पूरा माइक्रो-कार्यों से संकेत
- कॉल
abort
विधि के नियंत्रक रद्द करने के लिए सभी सदस्यता सूक्ष्म कार्य
यह काफी वाचाल और एक मुश्किल समाधान के साथ क्षमता स्मृति leaks.
मैं सिर्फ सुझाव है कि मेरा खुद का समाधान करने के लिए इस चुनौती- सी-promise2प्रदान करता है, जो रद्द वादों और एक रद्द विकल्प के लिए ECMA अतुल्यकालिक कार्यों - जनरेटर.
यहाँ एक बुनियादी उदाहरण के लिए (लाइव डेमो):
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();
गहराई से रद्द समाधान (सभी कार्य कर रहे हैं रद्दीकरण) (लाइव डेमो):
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);