bluebird中的.cancel方法

发布于 2022-09-02 13:31:25 字数 1572 浏览 22 评论 0

http://bluebirdjs.com/docs/api/cancellation.html

var searchPromise = Promise.resolve();  // Dummy promise to avoid null check.
document.querySelector("#search-input").addEventListener("input", function() {
    // The handlers of the previous request must not be called
    searchPromise.cancel();
    var url = "/search?term=" + encodeURIComponent(this.value.trim());
    showSpinner();
    searchPromise = makeCancellableRequest(url)
        .then(function(results) {
            return transformData(results);
        })
        .then(function(transformedData) {
            document.querySelector("#search-results").innerHTML = transformedData;
        })
        .catch(function(e) {
            document.querySelector("#search-results").innerHTML = renderErrorBox(e);
        })
        .finally(function() {
            // This check is necessary because `.finally` handlers are always called.
            if (!searchPromise.isCancelled()) {
                hideSpinner();
            }
        });
});

bluebird的文档是说,调用cancel方法后,前面的请求都不会执行,我按照例子来,还是执行了。

var Promise = require('bluebird');
var a = require('./a');
var b = require('./b');

var cancelPromise = Promise.resolve();
cancelPromise.cancel();
cancelPromise = a.fnA()
  .then(function() {
    return b.fnB();
  })
  .then(function() {
    console.log('done');
  })
  .finally(function() {
    if (cancelPromise.isCancelled()) {
      console.log('canceled');
    }
    console.log('end');
  });

姿势不对?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

美人迟暮 2022-09-09 13:31:25

默认情况下是关闭的,加上Promise.config({cancellation:true});这句即可。官方文档里有:

.cancel js .cancel() -> undefined Cancel this promise. Will not do anything if this promise is already settled or if the Cancellation feature has not been enabled. See Cancellation for how to use cancellation.

Cancellation Cancellation has been redesigned for bluebird 3.x, any code that relies on 2.x cancellation semantics won't work in 3.x. The cancellation feature is by default turned off, you can enable it using Promise.config.

demo:
clipboard.png
结果
clipboard.png

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文