第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

開心每一天1111 2021-10-21 16:11:05
假設(shè)我有一個搜索功能來進(jìn)行 HTTP 調(diào)用。每次調(diào)用可能需要不同的時間。所以我需要取消最后一個 HTTP 請求,只等待最后一個調(diào)用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已解決”我怎樣才能實現(xiàn)這個場景?
查看完整描述

3 回答

?
藍(lán)山帝景

TA貢獻(xiàn)1843條經(jīng)驗 獲得超7個贊

Promise 本身是不可取消的,但在有限的意義上會通過導(dǎo)致它們被拒絕來取消。


考慮到這一點,可以通過少量的詳細(xì)說明Promise.race()和您希望取消的承諾返回功能來實現(xiàn)取消。


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

    }

}

假設(shè)您的 http 調(diào)用函數(shù)已命名httpRequest(promise令人困惑):


const search = makeCancellable(httpRequest);

現(xiàn)在,每次search()調(diào)用時,都會調(diào)用緩存的reject可執(zhí)行文件以“取消”前面的搜索(如果它存在并且其競爭尚未完成)。


// 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 回調(diào)可以進(jìn)行測試err.message === '_cancelled_'以區(qū)分取消和其他拒絕原因。


查看完整回答
反對 回復(fù) 2021-10-21
  • 3 回答
  • 0 關(guān)注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號