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');
});
姿势不对?
默认情况下是关闭的,加上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:
结果