【问题标题】:Timeout a Promise if failed to complete in time如果未能及时完成,则超时 Promise
【发布时间】:2021-03-08 15:19:37
【问题描述】:

我有一个功能可以做到这一点:

this._getContainerData().then((data) => {
    this.__getIndexes(idx).forEach((indexVisible, index) => {
        this.containerData[indexVisible] = data[index]
    });
    if (this.horizontalRailIndex === idx) {
        this.container._setData(this.context);
    }
});

this._getContainerData() 返回一个承诺,并被多次调用。我想检查这个承诺是否需要超过 1000 毫秒 - 如果是这样,请取消它或返回一个空的承诺。我有一个名为CancelablePromise 的类,我可以像这样导入和使用它:new CancelablePromise,它确实有一个取消功能。如果您有任何其他建议,我将很高兴听到。

【问题讨论】:

标签: javascript promise timeout settimeout


【解决方案1】:

Demo1

import { CPromise } from "c-promise2";

const _getContainerData = () =>
  new CPromise((resolve, reject, { onCancel }) => {
    const timer = setTimeout(resolve, 2000, "myValue");

    onCancel((reason) => {
      console.log(`your cancel routine: ${reason}`);
      clearTimeout(timer);
    });
  });

_getContainerData()
  .timeout(1000)
  .then((data) => {
    console.log("then code");
  });

Demo2

import { CPromise, promisify } from "c-promise2";

const _getContainerData = promisify(function* (scope) {
  scope.onCancel((reason) => {
    console.log(`your cancel routine: ${reason}`);
  });
  // inner async routines
  console.log("start");
  yield new Promise((resolve) => setTimeout(resolve, 300));
  console.log("stage 1");
  yield new Promise((resolve) => setTimeout(resolve, 300));
  console.log("stage 2");
  yield new Promise((resolve) => setTimeout(resolve, 300));
  console.log("stage 3");
  yield new Promise((resolve) => setTimeout(resolve, 300));
  console.log("stage 4");
  yield new Promise((resolve) => setTimeout(resolve, 300));
  return "myValue";
});

const promise = _getContainerData()
  .timeout(1000)
  .then(
     data => console.log(`complete with: ${data}`), 
     err => console.warn(`Failed: ${err}`)
  );

// manual cancellation
// promise.cancel();

【讨论】:

    猜你喜欢
    • 2015-12-04
    • 2011-01-17
    • 2016-03-12
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 2014-09-19
    相关资源
    最近更新 更多