我正在学习这个 Bluebird promise 库。我创建了一个非常简单的 Express 应用程序,只有一个文件和一个路由 - GET /test
。
基本上我的场景是我有一个 promise ,里面有间隔,并在几个间隔“循环”后解决。间隔每 1 秒工作一次,5 次后我清除间隔并解决 promise 。
但是在我解决间隔中的 promise 之前,我有超时,应该在 3 秒后取消此 promise ,因此停止间隔。
我的代码是:
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配置here (因为默认情况下禁用取消)。
然后我有我的 foo 函数,里面有 bluebird promise 。我之前提到过间隔有这样的逻辑 - 索引号递增,当它是 5
时,间隔最终将解决 promise 。
但在此之前,在我的 /test
route ,我有超时,应该在 3 秒后取消此 promise 。
所以预期的输出是:
in interval, index: 1
in interval, index: 2
in interval, index: 3
Completed
但这实际上不起作用,并给我错误,它不知道取消方法是什么:
C:\Users\Admin\Documents\cancellationPromise\bluebirdp\server.js:35
foo.cancel(); ^
TypeError: foo.cancel is not a function
编辑
我已将 /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');
});
所以现在我正在对返回的 promise 调用取消。现在的行为是它在 55 毫秒后给出响应,然后每秒 console.log 不会在 3 处停止:
bluebird 是否可以取消 Promise,包括循环、间隔和其他嵌套的 Promise?
最佳答案
你取消了 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);
});
});
};
关于javascript - 与 Bluebird 库取消 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56089192/