적절한 방법으로 중단(정지)실행하는 비동기/여 기능이?

0

질문

이 있었 다른 항목에서 SE,그러나 그들의 대부분은 5 년 전입니다. 현재,그대로--날짜 접근 방식을 취소리에서 호출 JS? 즉

async myFunc(){
    let response = await oneHourLastingFunction();
    myProcessData(response);
}

에서 특정 응용 프로그램 순간을 결정 그것은 더 이상 기다리고 싶는 oneHourLastingFunction지만,그것은 갇혀서"기다리고". 는 방법을 취소하니까? 어떤 표준 방법 cancelation-토큰/abortControllers 에 대한 약속?

1

최고의 응답

1

을 취소하는 비동기적 절차가 여전히지 않은 간단한 작업,특히 필요로 할 때 당신은 깊은 취소 및 유량 조절을 할 수 있습니다. 없는 네이티브 솔루션니다. 당신이 할 수있는 모든 기본적으로:

  • 패 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);
2021-11-25 16:48:29

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................