bluebird中的.cancel方法
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下是关闭的,加上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:
结果