如果未解决,如何取消最后一个 Promise?

假设我有一个搜索功能来进行 HTTP 调用。每次调用可能需要不同的时间。所以我需要取消最后一个 HTTP 请求,只等待最后一个调用


async function search(timeout){


   const data = await promise(timeout)

   return data;


}

// the promise function is only for visualizing an http call

function promise(timeout){

   return new Promise(resolve,reject){

       setTimeout(function(){      

           resolve()

       },timeout) 

   }

}

search(200)

.then(function(){console.log('search1 resolved')})

.catch(function() {console.log('search1 rejected')})

search(2000)

.then(function(){console.log('search2 resolved')})

.catch(function(){console.log('search2 rejected')})

search(1000)

.then(function(){console.log('search3 resolved')})

.catch(function(){console.log('search3 rejected')})

需要看到“search1已解决”“search2被拒绝”“search3已解决”


我怎样才能实现这个场景?


开心每一天1111
浏览 159回答 3
3回答

蓝山帝景

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 calledsearch(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 calledsearch(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 calledsearch(1000).then(function() { console.log('search3 resolved') }).catch(function(err) { console.log('search3 rejected', err) });如有必要,catch 回调可以进行测试err.message === '_cancelled_'以区分取消和其他拒绝原因。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript