取消一个vanilla ECMAScript 6 Promise链

时间:2015-04-06 20:03:32

标签: javascript promise cancellation es6-promise

是否有方法清除JavaScript .then实例的Promise

我在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({{ 1}})仍在等待解决它。

我需要一个好方法取消我的测试。我可以通过在框架模块result上创建一个字段来完成它,并在测试中经常检查(例如在每个this.cancelTest迭代的开始)是否取消。但是,理想情况下,我可以使用then()清除$$(at).on("timeout", /* something here */)变量上剩余的then(),以便其余的测试都不会运行。

这样的事情是否存在?

快速更新

我尝试使用result。它不起作用。

更新2 +混乱

为了解锁我,我在测试构思中添加了几行Promise.race([result, at.promise]) / polling。 (我也删除了事件触发器。)

mod.cancelTest

我在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语句没有被调用。想法?

更新3

想出最后一件事。 then()抛出了一个我没有抓到的错误,因此测试承诺在fn.call()解决之前就拒绝了。

17 个答案:

答案 0 :(得分:53)

  

是否有清除JavaScript Promise实例的.then的方法?

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

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

在语言委员会找到最佳方式(ES7希望?)之前,你仍然可以使用userland Promise实现,其中许多都具有取消功能。

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

答案 1 :(得分:44)

虽然在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

答案 2 :(得分:7)

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

有没有一种清除方法,是的,您可以拒绝带有AbortController对象的promise,然后promise将绕过所有then块并直接转到陷阱块。

示例:

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,并非所有浏览器都支持。

实时示例

Edit elegant-lake-5jnh3

答案 3 :(得分:5)

我真的很惊讶没有人提到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 });

答案 4 :(得分:4)

有一些npm库用于可撤销的诺言。

  1. p可取消 https://github.com/sindresorhus/p-cancelable

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

答案 5 :(得分:4)

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

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('Fucked up!'));
}, 1000);

答案 6 :(得分:2)

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();

答案 7 :(得分:1)

简单版

只是给出拒绝功能。

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对象。它将具有取消功能。如果它有取消功能,那么它是可取消的。

此取消功能拒绝带有错误的承诺('已取消')。

在解决之前,拒绝或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')
})

答案 8 :(得分:1)

如果将代码放置在类中,则可以使用装饰器。 utils-decoratorsnpm install --save utils-decorators)中有这样的装饰器。如果在解决之前的调用之前,已再次调用该装饰方法,则它将取消装饰方法的先前调用。

import {cancelPrevious} from 'utils-decorators';

class SomeService {

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

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

答案 9 :(得分:0)

在Promise上设置“已取消”属性,以便then()catch()提前退出。它非常有效,特别是在Web Workers中,现有的微任务在onmessage处理程序的Promises中排队。

// 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;
}

答案 10 :(得分: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();

答案 11 :(得分:0)

这是我们的实施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来电
  • 中进一步取消
  • 依赖拒绝而非已解决取消,与其他提议或实施不同

拉动和评论欢迎

答案 12 :(得分:0)

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

答案 13 :(得分:0)

尝试一下:https://github.com/dondevi/promise-abortable

{
    "message": "An error has occurred.",
    "exceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
    "exceptionType": "System.InvalidOperationException",
    "stackTrace": null,
    "innerException": {
        "message": "An error has occurred.",
        "exceptionMessage": "Self referencing loop detected for property 'book' with type 'System.Data.Entity.DynamicProxies.Book_6E27A1F717202EA02AE923CCC6405EF9A501FE9A54A71841CEB43E942224D88A'. Path '[0].borrows[0]'.",
        "exceptionType": "Newtonsoft.Json.JsonSerializationException",
        "stackTrace": "   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter writer, Object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
...

答案 14 :(得分:0)

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

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

答案 15 :(得分:0)

我仍在研究这个想法,但是这里是我以setTimeout为例来实现可取消的Promise的方式。

这个想法是,只要您确定了承诺,承诺就会被解决或拒绝,因此应该确定要取消的时间,满足条件,然后自己调用reject()函数。

  • 首先,我认为有两个原因尽早完成承诺:将其兑现并完成(我称为 resolve )和取消(我称为< strong>拒绝)。当然,那只是我的感觉。当然,有一个Promise.resolve()方法,但是它在构造函数中,并返回一个虚拟的已解决的promise。该实例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>

答案 16 :(得分:0)

使用CPromise package,我们可以使用以下方法(Live demo

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(Live demo)也是一样

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);