3 回答
TA贡献1843条经验 获得超7个赞
Promise 本身是不可取消的,但在有限的意义上会通过导致它们被拒绝来取消。
考虑到这一点,可以通过少量的详细说明Promise.race()和您希望取消的承诺返回功能来实现取消。
function makeCancellable(fn) {
var reject_; // cache for the latest `reject` executable
return function(...params) {
if(reject_) reject_(new Error('_cancelled_')); // If previous reject_ exists, cancel it.
// Note, this has an effect only if the previous race is still pending.
let canceller = new Promise((resolve, reject) => { // create canceller promise
reject_ = reject; // cache the canceller's `reject` executable
});
return Promise.race([canceller, fn.apply(null, params)]); // now race the promise of interest against the canceller
}
}
假设您的 http 调用函数已命名httpRequest(promise令人困惑):
const search = makeCancellable(httpRequest);
现在,每次search()调用时,都会调用缓存的reject可执行文件以“取消”前面的搜索(如果它存在并且其竞争尚未完成)。
// Search 1: straightforward - nothing to cancel - httpRequest(200) is called
search(200)
.then(function() { console.log('search1 resolved') })
.catch(function(err) { console.log('search3 rejected', err) });
// Search 2: search 1 is cancelled and its catch callback fires - httpRequest(2000) is called
search(2000)
.then(function() { console.log('search2 resolved') })
.catch(function(err) { console.log('search3 rejected', err) });
// Search 3: search 2 is cancelled and its catch callback fires - httpRequest(1000) is called
search(1000)
.then(function() { console.log('search3 resolved') })
.catch(function(err) { console.log('search3 rejected', err) });
如有必要,catch 回调可以进行测试err.message === '_cancelled_'以区分取消和其他拒绝原因。
添加回答
举报