我想我误解了蓝鸟如何取消承诺。我写了一个测试来证明这一点。我如何让它变绿?感谢:
describe('cancellation tests', () => {
function fakeFetch() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 100);
});
}
function awaitAndAddOne(p1) {
return p1.then(res => res + 1);
}
it('`cancel` cancels promises higher up the chain', () => {
const p1 = fakeFetch();
const p2 = awaitAndAddOne(p1);
expect(p2.isCancellable()).toBeTruthy();
p2.cancel();
return p2
.then(() => {
console.error('then');
})
.catch(err => {
console.error(err);
})
.finally(() => {
expect(p2.isCancelled()).toBeTruthy(); // Expected value to be truthy, instead received false
expect(p1.isCancelled()).toBeTruthy();
});
});
});
答案 0 :(得分:1)
来自here:
默认情况下,取消功能已关闭,您可以使用Promise.config启用它。
好像你没有在Promise上启用cancellation
标志:
Promise.config({
cancellation: true
});
describe(...
答案 1 :(得分:0)
@Karen如果正确的话。但问题是你的测试也有点错误
如果你看一下isCancellable
方法
Promise.prototype.isCancellable = function() {
return this.isPending() && !this.isCancelled();
};
这只是检查promise
是否为pending
且尚未取消。这并不意味着启用取消。
http://bluebirdjs.com/docs/api/cancellation.html
如果你看到上面的网址,则引用下面的
取消功能默认情况下已关闭,您可以使用Promise.config启用它。
如果你看一下cancel
方法
Promise.prototype["break"] = Promise.prototype.cancel = function() {
if (!debug.cancellation()) return this._warn("cancellation is disabled");
现在,如果我将测试更新为正确如下
var Promise = require("bluebird");
var expect = require("expect");
describe('cancellation tests', () => {
function fakeFetch() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 100);
});
}
function awaitAndAddOne(p1) {
return p1.then(res => res + 1);
}
it('`cancel` cancels promises higher up the chain', () => {
const p1 = fakeFetch();
const p2 = awaitAndAddOne(p1);
value = p2.isCancellable();
expect(p2.isCancellable()).toBeTruthy();
p2.cancel();
expect(p2.isCancelled()).toBeTruthy(); // Expected value to be truthy, instead received false
expect(p1.isCancelled()).toBeTruthy();
});
});
您可以看到取消未启用,它会执行警告代码
执行结果按预期失败
spec.js:46
cancellation tests
spec.js:46
1) `cancel` cancels promises higher up the chain
spec.js:78
0 passing (3m)
base.js:354
1 failing
base.js:370
1) cancellation tests
base.js:257
`cancel` cancels promises higher up the chain:
Error: expect(received).toBeTruthy()
Expected value to be truthy, instead received
false
at Context.it (test/index.test.js:37:36)
现在,如果您更新代码以启用取消
var Promise = require("bluebird");
var expect = require("expect");
Promise.config({
cancellation: true
});
describe('cancellation tests', () => {
function fakeFetch() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 100);
});
}
function awaitAndAddOne(p1) {
return p1.then(res => res + 1);
}
it('`cancel` cancels promises higher up the chain', () => {
const p1 = fakeFetch();
const p2 = awaitAndAddOne(p1);
value = p2.isCancellable();
expect(p2.isCancellable()).toBeTruthy();
p2.cancel();
expect(p2.isCancelled()).toBeTruthy(); // Expected value to be truthy, instead received false
expect(p1.isCancelled()).toBeTruthy();
});
});
有效!