【问题标题】:Promise cancellation with bluebird library使用蓝鸟图书馆取消承诺
【发布时间】:2019-09-29 01:08:07
【问题描述】:

我正在学习这个 bluebird promise 库。我创建了一个非常简单的快速应用程序,只有一个文件和一个路由 - GET /test

基本上,我的场景是我有一个承诺,其中有间隔,并在几个间隔“循环”后解决。间隔每 1 秒工作一次,5 次后我清除间隔并解决承诺。

但在我从间隔解决承诺之前,我有超时,应该在 3 秒后取消这个承诺,因此停止间隔。

我的代码是:

const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const Promise = require('bluebird');

Promise.config({
    warnings: true,
    longStackTraces: true,
    cancellation: true,
    monitoring: true
});

app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));

//promise
const foo = () => {
    return new Promise((resolve, reject) => {
        let index = 0;
        const intervalId = setInterval(() => {
            index++;
            console.log('in interval, index: ', index);
            if(index === 5) {
                clearInterval(intervalId);
                resolve();
            }
        }, 1000);
    });
};

//test route here
app.get('/test', async(req, res) => {
    setTimeout(() => {
        foo.cancel();
    }, 3000);
    try {
        await foo();    
    } catch (e) {
        console.error(e);
    }
    res.send('Completed');
});

app.listen(5000, () => {
    console.log('Listen on port: ', 5000)
});

所以首先我需要 express 和 node 包,然后我按照他们的建议设置 bluebird config here(因为默认情况下禁用取消)。

然后我有我的 foo 函数,里面有 bluebird 承诺。我之前提到的间隔有这个逻辑 - 索引号在递增,当它是 5 时,间隔将最终解决承诺。

但在此之前,在我的 /test 路由中,我有超时,应该在 3 秒后取消这个承诺。

所以预期的输出是:

在区间内,索引:1

在区间内,索引:2

在区间内,索引:3

完成

但这实际上不起作用,并给我一个错误,它不知道取消方法是什么:

C:\Users\Admin\Documents\cancellationPromise\bluebirdp\server.js:35

   foo.cancel();

       ^

TypeError: foo.cancel 不是函数

编辑 我已将 /test 路由更改为:

app.get('/test', async(req, res) => {
    let searchPromise = Promise.resolve();
    searchPromise = foo()
        .then(function() {
            console.log('not canceled')
        })
        .catch(function(e) {
            console.log(e);
        })
        .finally(function() {
            if (!searchPromise.isCancelled()) {}
        });

    setTimeout(() => {
        searchPromise.cancel();
    }, 3000);

    res.send('Completed');
});

所以现在我在返回的承诺上调用取消。现在的行为是它在 55 毫秒后给出响应,然后每秒 console.log 不会在 3 停止:

bluebird 是否可以取消 Promise,包括循环、间隔和其他嵌套的 Promise?

【问题讨论】:

  • foo 是一个函数,而不是一个承诺。您可能想在foo() 返回的promise 对象上调用.cancel() 方法?
  • 哦,实际上
  • 我更改了我的代码,但我仍然无法用 bluebird 取消它,请给一些提示@Bergi

标签: javascript node.js promise bluebird cancellation


【解决方案1】:

您取消了 Promise,但您从未清除间隔。这两件事在您的代码中没有正确链接。它应该是这样的:

const foo = () => {
  return new Promise((resolve, reject, onCancel) => {
    let index = 0;
    const intervalId = setInterval(() => {
      index++;
      console.log('in interval, index: ', index);
      if(index === 5) {
        clearInterval(intervalId);
        resolve();
      }
    }, 1000);
    onCancel(() => {
      clearInterval(intervalId);
    });
  });
};

【讨论】:

    猜你喜欢
    • 2015-02-13
    • 2018-10-23
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 2014-02-13
    • 2014-11-06
    相关资源
    最近更新 更多