亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果未解決,如何取消最后一個 Promise?

如果未解決,如何取消最后一個 Promise?

開心每一天1111 2021-10-21 16:11:05
假設我有一個搜索功能來進行 HTTP 調用。每次調用可能需要不同的時間。所以我需要取消最后一個 HTTP 請求,只等待最后一個調用async function search(timeout){   const data = await promise(timeout)   return data;}// the promise function is only for visualizing an http callfunction 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已解決”我怎樣才能實現這個場景?
查看完整描述

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_'以區分取消和其他拒絕原因。


查看完整回答
反對 回復 2021-10-21
  • 3 回答
  • 0 關注
  • 184 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號