promise 靜態(tài)方法 原型方法

靜態(tài)方法:resolve/reject/race/all

Promise.resolve()?and?Promise.reject()?are shortcuts to manually create an already resolved or rejected promise respectively.

Promise.resolve()
Promise.reject()不區(qū)分接受值
Promise.all() Promise.race()

Promise.all()?and?Promise.race()?are two composition tools for running asynchronous operations in parallel.

We can start operations in parallel and wait for them all to finish like this:

Promise.all([func1(),func2(),func3()])

.then(([result1,result2,result3])=>{/* use result1, result2 and result3 */});


Sequential composition is possible using some clever JavaScript:

[func1,func2,func3].reduce((p,f) =>?

????p.then(f),

????Promise.resolve()

).then(result3=>{/* use result3 */});

Basically, we reduce an array of asynchronous functions down to a promise chain equivalent to:?

Promise.resolve().then(func1).then(func2).then(func3);


向Promise.all([])傳入空數(shù)組,它會(huì)立即完成;但Promise.race([])會(huì)掛住,且永遠(yuǎn)不會(huì)決議


原型方法:catch/then/finally

promise.then({return 1;})的返回值

每個(gè)方法中return的值不僅只局限于字符串或者數(shù)值類型,也可以是對(duì)象或者promise對(duì)象等復(fù)雜類型。

return的值會(huì)由Promise.resolve(return的返回值);進(jìn)行相應(yīng)的包裝處理,因此不管回調(diào)函數(shù)中會(huì)返回一個(gè)什么樣的值,最終then的結(jié)果都是返回一個(gè)新創(chuàng)建的promise對(duì)象。

Promise.then不僅僅是注冊(cè)一個(gè)回調(diào)函數(shù)那么簡(jiǎn)單,它還會(huì)將回調(diào)函數(shù)的返回值進(jìn)行變換,創(chuàng)建并返回一個(gè)promise對(duì)象。


then和catch的參數(shù)的區(qū)別?

Promise.prototype.then(),作用是為Promise實(shí)例添加狀態(tài)改變的回調(diào)函數(shù),then方法的第一個(gè)參數(shù)是resolved狀態(tài)函數(shù),第二個(gè)參數(shù)為可選值,是rejected狀態(tài)的回調(diào)函數(shù)

Promise.prototype.catch方法是.then(null,rejected)或.then(undefined,rejected)的別名,用于發(fā)生錯(cuò)誤時(shí)的回調(diào)函數(shù)


Promise中拋出異常能否被catch捕獲?catch會(huì)處理鏈之前的任何的reject

let promise = new Promise((resolve, reject) => {

??throw new Error()

??reject()

})

promise.catch(err => {

??console.log(err)

})


promise如何中斷某個(gè)then,代碼實(shí)現(xiàn)promise封裝一個(gè)callback

怎么取消一個(gè)Promise

實(shí)現(xiàn)Promise的cancel方法,調(diào)用后停止繼續(xù)執(zhí)行then上掛載的callback

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容