135

是否有清除.thenJavaScriptPromise实例的 s 的方法?

我在QUnit之上编写了一个 JavaScript 测试框架。该框架通过在Promise. (对不起这个代码块的长度。我尽我所能评论它,所以感觉不那么乏味。)

/* Promise extension -- used for easily making an async step with a
       timeout without the Promise knowing anything about the function 
       it's waiting on */
$$.extend(Promise, {
    asyncTimeout: function (timeToLive, errorMessage) {
        var error = new Error(errorMessage || "Operation timed out.");
        var res, // resolve()
            rej, // reject()
            t,   // timeout instance
            rst, // reset timeout function
            p,   // the promise instance
            at;  // the returned asyncTimeout instance

        function createTimeout(reject, tempTtl) {
            return setTimeout(function () {
                // triggers a timeout event on the asyncTimeout object so that,
                // if we want, we can do stuff outside of a .catch() block
                // (may not be needed?)
                $$(at).trigger("timeout");

                reject(error);
            }, tempTtl || timeToLive);
        }

        p = new Promise(function (resolve, reject) {
            if (timeToLive != -1) {
                t = createTimeout(reject);

                // reset function -- allows a one-time timeout different
                //    from the one original specified
                rst = function (tempTtl) {
                    clearTimeout(t);
                    t = createTimeout(reject, tempTtl);
                }
            } else {
                // timeToLive = -1 -- allow this promise to run indefinitely
                // used while debugging
                t = 0;
                rst = function () { return; };
            }

            res = function () {
                clearTimeout(t);
                resolve();
            };

            rej = reject;
        });

        return at = {
            promise: p,
            resolve: res,
            reject: rej,
            reset: rst,
            timeout: t
        };
    }
});

/* framework module members... */

test: function (name, fn, options) {
    var mod = this; // local reference to framework module since promises
                    // run code under the window object

    var defaultOptions = {
        // default max running time is 5 seconds
        timeout: 5000
    }

    options = $$.extend({}, defaultOptions, options);

    // remove timeout when debugging is enabled
    options.timeout = mod.debugging ? -1 : options.timeout;

    // call to QUnit.test()
    test(name, function (assert) {
        // tell QUnit this is an async test so it doesn't run other tests
        // until done() is called
        var done = assert.async();
        return new Promise(function (resolve, reject) {
            console.log("Beginning: " + name);

            var at = Promise.asyncTimeout(options.timeout, "Test timed out.");
            $$(at).one("timeout", function () {
                // assert.fail() is just an extension I made that literally calls
                // assert.ok(false, msg);
                assert.fail("Test timed out");
            });

            // run test function
            var result = fn.call(mod, assert, at.reset);

            // if the test returns a Promise, resolve it before resolving the test promise
            if (result && result.constructor === Promise) {
                // catch unhandled errors thrown by the test so future tests will run
                result.catch(function (error) {
                    var msg = "Unhandled error occurred."
                    if (error) {
                        msg = error.message + "\n" + error.stack;
                    }

                    assert.fail(msg);
                }).then(function () {
                    // resolve the timeout Promise
                    at.resolve();
                    resolve();
                });
            } else {
                // if test does not return a Promise, simply clear the timeout
                // and resolve our test Promise
                at.resolve();
                resolve();
            }
        }).then(function () {
            // tell QUnit that the test is over so that it can clean up and start the next test
            done();
            console.log("Ending: " + name);
        });
    });
}

如果测试超时,我的超时 Promise 将assert.fail()在测试上,以便将测试标记为失败,这一切都很好,但是测试继续运行,因为测试 Promise ( result) 仍在等待解决它。

我需要一个取消考试的好方法。我可以通过在框架模块this.cancelTest或其他东西上创建一个字段来做到这一点,并在测试中每隔一段时间检查一次(例如在每次then()迭代开始时)是否取消。但是,理想情况下,我可以$$(at).on("timeout", /* something here */)用来清除变量上剩余then()的 s result,这样就不会运行其余的测试。

这样的事情存在吗?

快速更新

我尝试使用Promise.race([result, at.promise]). 它没有用。

更新 2 + 混乱

为了解除对我的阻止,我在测试想法中添加了几行mod.cancelTest/polling。(我还删除了事件触发器。)

return new Promise(function (resolve, reject) {
    console.log("Beginning: " + name);

    var at = Promise.asyncTimeout(options.timeout, "Test timed out.");
    at.promise.catch(function () {
        // end the test if it times out
        mod.cancelTest = true;
        assert.fail("Test timed out");
        resolve();
    });

    // ...
    
}).then(function () {
    // tell QUnit that the test is over so that it can clean up and start the next test
    done();
    console.log("Ending: " + name);
});

我在语句中设置了一个断点catch,它被击中了。现在让我感到困惑的是,该then()声明没有被调用。想法?

更新 3

想通了最后一件事。 fn.call()抛出了一个我没有发现的错误,所以测试承诺在at.promise.catch()解决它之前被拒绝。

4

17 回答 17

92

是否有清除.thenJavaScript Promise 实例的 s 的方法?

不,至少在 ECMAScript 6 中没有。Promise(及其then处理程序)默认情况下是不可取消的(不幸的是)。在 es-discuss(例如这里)上有一些关于如何以正确的方式做到这一点的讨论,但无论哪种方法会获胜,它都不会在 ES6 中落地。

当前的观点是,子类化将允许使用您自己的实现创建可取消的承诺(不确定这将如何运作)

在语言委员会找到最好的方法(希望是 ES7?)之前,您仍然可以使用用户态 Promise 实现,其中许多功能取消。

当前的讨论在https://github.com/domenic/cancelable-promisehttps://github.com/bergus/promise-cancellation草案中。

于 2015-04-06T20:49:36.057 回答
59

虽然在 ES6 中没有标准的方法来做这件事,但有一个名为Bluebird的库来处理这个问题。

还有一种推荐的方式被描述为反应文档的一部分。它看起来与您在第 2 次和第 3 次更新中的相似。

const makeCancelable = (promise) => {
  let hasCanceled_ = false;

  const wrappedPromise = new Promise((resolve, reject) => {
    promise.then((val) =>
      hasCanceled_ ? reject({isCanceled: true}) : resolve(val)
    );
    promise.catch((error) =>
      hasCanceled_ ? reject({isCanceled: true}) : reject(error)
    );
  });

  return {
    promise: wrappedPromise,
    cancel() {
      hasCanceled_ = true;
    },
  };
};

const cancelablePromise = makeCancelable(
  new Promise(r => component.setState({...}}))
);

cancelablePromise
  .promise
  .then(() => console.log('resolved'))
  .catch((reason) => console.log('isCanceled', reason.isCanceled));

cancelablePromise.cancel(); // Cancel the promise

取自:https ://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html

于 2016-05-27T21:19:18.283 回答
24

我真的很惊讶没有人提到Promise.race这个候选人:

const actualPromise = new Promise((resolve, reject) => { setTimeout(resolve, 10000) });
let cancel;
const cancelPromise = new Promise((resolve, reject) => {
    cancel = reject.bind(null, { canceled: true })
})

const cancelablePromise = Object.assign(Promise.race([actualPromise, cancelPromise]), { cancel });
于 2018-04-16T20:09:37.847 回答
13
const makeCancelable = promise => {
    let rejectFn;

    const wrappedPromise = new Promise((resolve, reject) => {
        rejectFn = reject;

        Promise.resolve(promise)
            .then(resolve)
            .catch(reject);
    });

    wrappedPromise.cancel = () => {
        rejectFn({ canceled: true });
    };

    return wrappedPromise;
};

用法:

const cancelablePromise = makeCancelable(myPromise);
// ...
cancelablePromise.cancel();
于 2019-06-06T09:41:13.670 回答
13

可以在 的帮助下取消承诺AbortController

那么有没有一种清除方法: 是的,您可以用对象拒绝承诺,AbortController然后promise将绕过所有 then 块并直接进入 catch 块。

例子:

import "abortcontroller-polyfill";

let controller = new window.AbortController();
let signal = controller.signal;
let elem = document.querySelector("#status")

let example = (signal) => {
    return new Promise((resolve, reject) => {
        let timeout = setTimeout(() => {
            elem.textContent = "Promise resolved";
            resolve("resolved")
        }, 2000);

        signal.addEventListener('abort', () => {
            elem.textContent = "Promise rejected";
            clearInterval(timeout);
            reject("Promise aborted")
        });
    });
}

function cancelPromise() {
    controller.abort()
    console.log(controller);
}

example(signal)
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.log("Catch: ", error)
    });

document.getElementById('abort-btn').addEventListener('click', cancelPromise);

html


    <button type="button" id="abort-btn" onclick="abort()">Abort</button>
    <div id="status"> </div>

注意:需要添加 polyfill,并非所有浏览器都支持。

现场示例

编辑优雅湖 5jnh3

于 2020-01-31T07:23:54.073 回答
8

实际上不可能停止 Promise 的执行,但是您可以劫持拒绝并从 Promise 本身调用它。

class CancelablePromise {
  constructor(executor) {
    let _reject = null;
    const cancelablePromise = new Promise((resolve, reject) => {
      _reject = reject;
      return executor(resolve, reject);
    });
    cancelablePromise.cancel = _reject;

    return cancelablePromise;
  }
}

用法:

const p = new CancelablePromise((resolve, reject) => {
  setTimeout(() => {
    console.log('resolved!');
    resolve();
  }, 2000);
})

p.catch(console.log);

setTimeout(() => {
  p.cancel(new Error('Messed up!'));
}, 1000);
于 2019-08-12T10:26:41.617 回答
3

有一些用于可取消承诺的 npm 库。

  1. p-cancelable https://github.com/sindresorhus/p-cancelable

  2. 可取消承诺 https://github.com/alkemics/CancelablePromise

于 2018-11-29T11:46:12.337 回答
2

简单版

只需给出拒绝功能。

简单的想法:

function MyPromise(myparams,cancel_holder) {
 return new Promise(function(resolve,reject){
  //do work here
  cancel_holder.cancel=reject
 }
}

或简单的想法2:

function MyPromise() {
 var cancel_holder={};
 var promise=new Promise(function(resolve,reject){
  //do work here
  cancel_holder.cancel=reject;
 }
 promise.cancel=function(){ cancel_holder.cancel(); }
 return promise;
}

例子:

function Sleep(ms,cancel_holder) {

 return new Promise(function(resolve,reject){
  var done=false; 
  var t=setTimeout(function(){if(done)return;done=true;resolve();}, ms);
  cancel_holder.cancel=function(){if(done)return;done=true;if(t)clearTimeout(t);reject();} 
 })
}

包装解决方案(工厂)

我找到的解决方案是传递一个 cancel_holder 对象。它将具有取消功能。如果它具有取消功能,那么它是可取消的。

此取消函数以 Error('canceled') 拒绝承诺。

在 resolve、reject 或 on_cancel 之前,防止无故调用取消函数。

我发现通过注入传递取消操作很方便

function cancelablePromise(cancel_holder,promise_fn,optional_external_cancel) {
  if(!cancel_holder)cancel_holder={};
  return new Promise( function(resolve,reject) {
    var canceled=false;
    var resolve2=function(){ if(canceled) return; canceled=true; delete cancel_holder.cancel; resolve.apply(this,arguments);}
    var reject2=function(){ if(canceled) return; canceled=true; delete cancel_holder.cancel; reject.apply(this,arguments);}
    var on_cancel={}
    cancel_holder.cancel=function(){
      if(canceled) return; canceled=true;

      delete cancel_holder.cancel;
      cancel_holder.canceled=true;

      if(on_cancel.cancel)on_cancel.cancel();
      if(optional_external_cancel)optional_external_cancel();

      reject(new Error('canceled'));
    };
    
    return promise_fn.call(this,resolve2,reject2,on_cancel);        
  });
}
 
function Sleep(ms,cancel_holder) {

 return cancelablePromise(cancel_holder,function(resolve,reject,oncacnel){

  var t=setTimeout(resolve, ms);
  oncacnel.cancel=function(){if(t)clearTimeout(t);}     

 })
}


let cancel_holder={};

// meanwhile in another place it can be canceled
setTimeout(function(){  if(cancel_holder.cancel)cancel_holder.cancel(); },500) 

Sleep(1000,cancel_holder).then(function() {
 console.log('sleept well');
}, function(e) {
 if(e.message!=='canceled') throw e;
 console.log('sleep interrupted')
})
于 2017-09-19T09:40:39.063 回答
1

这是我们的实现https://github.com/permettez-moi-de-construire/cancellable-promise

像这样使用

const {
  cancellablePromise,
  CancelToken,
  CancelError
} = require('@permettezmoideconstruire/cancellable-promise')

const cancelToken = new CancelToken()

const initialPromise = SOMETHING_ASYNC()
const wrappedPromise = cancellablePromise(initialPromise, cancelToken)


// Somewhere, cancel the promise...
cancelToken.cancel()


//Then catch it
wrappedPromise
.then((res) => {
  //Actual, usual fulfill
})
.catch((err) => {
  if(err instanceOf CancelError) {
    //Handle cancel error
  }

  //Handle actual, usual error
})

哪个 :

  • 不触及 Promise API
  • 让我们在catch通话中进一步取消
  • 与任何其他提案或实施不同,依靠取消被拒绝而不是解决

欢迎拉取和评论

于 2018-03-26T08:47:43.247 回答
1

在 Promise 上设置“cancelled”属性以发出信号then()catch()提前退出。onmessage它非常有效,尤其是在 Web Worker 中,现有微任务在处理程序的 Promise 中排队。

// Queue task to resolve Promise after the end of this script
const promise = new Promise(resolve => setTimeout(resolve))

promise.then(_ => {
  if (promise.canceled) {
    log('Promise cancelled.  Exiting early...');
    return;
  }

  log('No cancelation signaled.  Continue...');
})

promise.canceled = true;

function log(msg) {
  document.body.innerHTML = msg;
}

于 2018-03-30T17:15:42.530 回答
1

我仍在研究这个想法,但这里是我如何实现一个可取消的 Promise 使用setTimeout的例子。

这个想法是只要你决定一个承诺就会被解决或拒绝,所以应该决定何时要取消,满足标准,然后reject()自己调用函数。

  • 首先,我认为提前完成承诺有两个原因:完成并完成(我称之为resolve)和取消(我称之为reject)。当然,这只是我的感觉。当然有一个Promise.resolve()方法,但它在构造函数本身中,并返回一个虚拟的已解析承诺。这个实例resolve()方法实际上解析了一个实例化的 Promise 对象。

  • 其次,您可以在返回新创建的 Promise 对象之前愉快地添加任何您喜欢的内容,因此我刚刚添加了一些resolve()方法reject()来使其自包含。

  • 第三,诀窍是以后能够访问执行器resolvereject函数,所以我只是将它们存储在闭包内的一个简单对象中。

我认为解决方案很简单,我看不出有什么大问题。

function wait(delay) {
  var promise;
  var timeOut;
  var executor={};
  promise=new Promise(function(resolve,reject) {
    console.log(`Started`);
    executor={resolve,reject};  //  Store the resolve and reject methods
    timeOut=setTimeout(function(){
      console.log(`Timed Out`);
      resolve();
    },delay);
  });
  //  Implement your own resolve methods,
  //  then access the stored methods
      promise.reject=function() {
        console.log(`Cancelled`);
        clearTimeout(timeOut);
        executor.reject();
      };
      promise.resolve=function() {
        console.log(`Finished`);
        clearTimeout(timeOut);
        executor.resolve();
      };
  return promise;
}

var promise;
document.querySelector('button#start').onclick=()=>{
  promise=wait(5000);
  promise
  .then(()=>console.log('I have finished'))
  .catch(()=>console.log('or not'));
};
document.querySelector('button#cancel').onclick=()=>{ promise.reject(); }
document.querySelector('button#finish').onclick=()=>{ promise.resolve(); }
<button id="start">Start</button>
<button id="cancel">Cancel</button>
<button id="finish">Finish</button>

于 2020-04-08T05:46:27.910 回答
0

@Michael Yagudaev 的回答对我有用。

但是最初的答案并没有将包装好的承诺与 .catch() 联系起来来处理拒绝处理,这是我对@Michael Yagudaev 答案的改进:

const makeCancelablePromise = promise => {
  let hasCanceled = false;
  const wrappedPromise = new Promise((resolve, reject) => {
    promise
      .then(val => (hasCanceled ? reject({ isCanceled: true }) : resolve(val)))
      .catch(
        error => (hasCanceled ? reject({ isCanceled: true }) : reject(error))
      );
  });

  return {
    promise: wrappedPromise,
    cancel() {
      hasCanceled = true;
    }
  };
};

// Example Usage:
const cancelablePromise = makeCancelable(
  new Promise((rs, rj) => {
    /*do something*/
  })
);
cancelablePromise.promise.then(() => console.log('resolved')).catch(err => {
  if (err.isCanceled) {
    console.log('Wrapped promise canceled');
    return;
  }
  console.log('Promise was not canceled but rejected due to errors: ', err);
});
cancelablePromise.cancel();
于 2018-08-03T08:50:52.787 回答
0

如果 p 是一个包含 Promise 的变量,那么p.then(empty);当它最终完成或者它已经完成时应该解除这个 Promise(是的,我知道这不是最初的问题,但这是我的问题)。“空”是function empty() {}。我只是一个初学者,可能是错的,但这些其他答案似乎太复杂了。承诺应该很简单。

于 2018-12-20T13:17:02.703 回答
0

尝试promise-abortablehttps ://www.npmjs.com/package/promise-abortable

$ npm install promise-abortable
import AbortablePromise from "promise-abortable";

const timeout = new AbortablePromise((resolve, reject, signal) => {
  setTimeout(reject, timeToLive, error);
  signal.onabort = resolve;
});

Promise.resolve(fn()).then(() => {
  timeout.abort();
});
于 2019-06-28T16:42:08.540 回答
0

如果您的代码放在一个类中,您可以为此使用装饰器。您在utils-decorators ( npm install --save utils-decorators) 中有这样的装饰器。如果在解决上一个调用之前对该特定方法进行了另一个调用,它将取消对装饰方法的上一次调用。

import {cancelPrevious} from 'utils-decorators';

class SomeService {

   @cancelPrevious()
   doSomeAsync(): Promise<any> {
    ....
   }
}

或者您可以使用包装函数:

import {cancelPreviousify} from 'utils-decorators';

const cancelable = cancelPreviousify(originalMethod)

https://github.com/vlio20/utils-decorators#cancelprevious-method

于 2020-04-16T04:25:50.933 回答
-1

如果你想阻止所有 thens/catchs 被执行,你可以通过注入一个永远不会解决的 Promise 来做到这一点。它可能有内存泄漏reprocusions,但它会解决问题,并且不会在大多数应用程序中造成过多的内存浪费。

new Promise((resolve, reject) => {
    console.log('first chain link executed')
    resolve('daniel');
}).then(name => {
    console.log('second chain link executed')
    if (name === 'daniel') {
        // I don't want to continue the chain, return a new promise
        // that never calls its resolve function
        return new Promise((resolve, reject) => {
            console.log('unresolved promise executed')
        });
    }
}).then(() => console.log('last chain link executed'))

// VM492:2 first chain link executed
// VM492:5 second chain link executed
// VM492:8 unresolved promise executed
于 2017-04-13T17:32:23.167 回答
-1

使用CPromise 包我们可以使用以下方法(现场演示

import CPromise from "c-promise2";

const chain = new CPromise((resolve, reject, { onCancel }) => {
  const timer = setTimeout(resolve, 1000, 123);
  onCancel(() => clearTimeout(timer));
})
  .then((value) => value + 1)
  .then(
    (value) => console.log(`Done: ${value}`),
    (err, scope) => {
      console.warn(err); // CanceledError: canceled
      console.log(`isCanceled: ${scope.isCanceled}`); // true
    }
  );

setTimeout(() => {
  chain.cancel();
}, 100);

使用 AbortController 做同样的事情(现场演示

import CPromise from "c-promise2";

const controller= new CPromise.AbortController();

new CPromise((resolve, reject, { onCancel }) => {
  const timer = setTimeout(resolve, 1000, 123);
  onCancel(() => clearTimeout(timer));
})
  .then((value) => value + 1)
  .then(
    (value) => console.log(`Done: ${value}`),
    (err, scope) => {
      console.warn(err);
      console.log(`isCanceled: ${scope.isCanceled}`);
    }
  ).listen(controller.signal);

setTimeout(() => {
  controller.abort();
}, 100);
于 2020-11-25T16:15:57.927 回答