을 취소하는 비동기적 절차가 여전히지 않은 간단한 작업,특히 필요로 할 때 당신은 깊은 취소 및 유량 조절을 할 수 있습니다. 없는 네이티브 솔루션니다. 당신이 할 수있는 모든 기본적으로:
- 패 AbortController 인스턴스를 각각의 중첩된 비동기 원하는 기능을 만드는 취소
- 가입 모든 내부 마이크로 작업(요청,타이머,etc.)신호
- 필요에 따라 탈퇴를 완료 마이크로에서 작업을 신호
- 전화
abort
방법은 컨트롤러를 취소하는 모든 구독 micro-작업
이것은 아주 자세한 정보고 까다로운 솔루션을 가진 잠재적인 메모리 누수를 방지합니다.
나는 그냥 좋 내 자신의 솔루션이 도전- c-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);