Promise 特性整理總結(jié)及心得用法

Promise對(duì)象

特性

Promise為es6標(biāo)準(zhǔn)語法,主要用于解決異步回調(diào)問題,Promise 對(duì)象可分為三種狀態(tài)。pending(進(jìn)行中)、fulfilled(已成功)和rejected(已失?。?,Promise 狀態(tài)為不可逆的,也就是說promise只能從pending->fulfilled,或從 pending -> rejected 由于異步操作的結(jié)果決定狀態(tài)。一旦狀態(tài)改變此對(duì)象將不能在復(fù)用。

示例

Promist 的基本用法本文章就不多做解釋,總結(jié)其中特性。

    let waitServerResponse = function(waitTime){
        return new Promise((resolve, reject)=>{
            if(waitTime>0){
                setTimeout(()=>{
                    resolve(`服務(wù)器響應(yīng)耗時(shí):${waitTime}`)
                },waitTime)
            }else {
                reject('系統(tǒng)故障')
            }
        })
    }
    waitServerResponse(3000).then((result)=>{
        console.log(result)     // 服務(wù)器響應(yīng)耗時(shí):3000
    })

    waitServerResponse(-1).then((success)=>{
        console.log('進(jìn)入success',success)
    }).catch((err)=>{
        console.log('捕獲到失敗狀態(tài):',err)  // 捕獲到失敗狀態(tài): 系統(tǒng)故障
    })

    console.log('程序結(jié)束!')

 /**
  * 控制臺(tái)輸出:
  * 捕獲到失敗狀態(tài): 系統(tǒng)故障
  * console.log('程序結(jié)束!')
  * 服務(wù)器響應(yīng)耗時(shí):3000
  */

由以上例子可以得出結(jié)論當(dāng)我們發(fā)起一個(gè)Promise操作時(shí) .then() 會(huì)在本輪 Javascript event loop(事件循環(huán))運(yùn)行完成才會(huì)執(zhí)行,promise并不會(huì)阻塞后面代碼執(zhí)行,因此在我們想要執(zhí)行類似請(qǐng)求執(zhí)行完成得到某某結(jié)果后,在執(zhí)行其他邏輯,就必須寫在then函數(shù)里。

// 強(qiáng)烈不推薦使用此種嵌套寫法用于工作中
    waitServerResponse(3000).then((result)=>{
        console.log(result)
        waitServerResponse(-1).then((success)=>{
            console.log('進(jìn)入success',success)
        }).catch((err)=>{
            console.log('捕獲到失敗狀態(tài):',err)  // 捕獲到失敗狀態(tài): 系統(tǒng)故障
            console.log('程序結(jié)束!')
        })
    })
 /**
  * 控制臺(tái)輸出:
  * 服務(wù)器響應(yīng)耗時(shí):3000
  * 捕獲到失敗狀態(tài): 系統(tǒng)故障
  * 程序結(jié)束!
  */

如果你一直都只是在這樣使用promise那你并不能稱得上會(huì)使用Promise這種用法同Ajax中請(qǐng)求中的回調(diào)函數(shù)如出一轍。根本就沒有解決回調(diào)地獄的問題。(筆者在很長(zhǎng)一段時(shí)間也用這種方式,并自以為樂??????)

鏈?zhǔn)秸{(diào)用

promise設(shè)計(jì)的目的就是想通過鏈?zhǔn)秸{(diào)用來解決回調(diào)問題。我們可以在then函數(shù)返回一個(gè)全新的promise來創(chuàng)造一個(gè)Promise chain。

    waitServerResponse(3000).then((result)=>{
        console.log(result)
        return waitServerResponse(-1)  // 使用return 創(chuàng)造 promise chain
    }).then((success)=>{
        console.log('進(jìn)入success',success)
    }).catch((err)=>{
        console.log('捕獲到失敗狀態(tài):',err)  // 捕獲到失敗狀態(tài): 系統(tǒng)故障
        console.log('程序結(jié)束!')
    })
// 還可以使用 => 語法 更加簡(jiǎn)化
    waitServerResponse(3000)
        .then(result => waitServerResponse(-1))
        .then(success => console.log('進(jìn)入success',success))
        .catch(err => console.log('程序結(jié)束!'))

通過Promise chain 可以解決兩個(gè)異步操作之前串行的問題,下面是Promise并行的場(chǎng)景。

組合

我當(dāng)我門同時(shí)向服務(wù)器發(fā)送三次請(qǐng)求 請(qǐng)求分別要等待 3s、2s、1s,獲取到全部數(shù)據(jù)后再執(zhí)行相應(yīng)操作。此時(shí)使用Promise chain理論耗時(shí)6s顯然是不可取的,Promise提供了all()方法解決并行問題。

    let request1 = waitServerResponse(3000)
    let request2 = waitServerResponse(2000)
    let request3 = waitServerResponse(1000)
    
    Promise.all([request1,request2,request3,]).then((values) => {
            console.log(values)  // ["服務(wù)器響應(yīng)耗時(shí):3000", "服務(wù)器響應(yīng)耗時(shí):2000", "服務(wù)器響應(yīng)耗時(shí):1000"]
        }
    )
  // 其中有任何promise狀態(tài)為失敗 都會(huì)被catch捕獲
    let request1 = waitServerResponse(3000)
    let request2 = waitServerResponse(2000)
    let request3 = waitServerResponse(-1)

    Promise.all([request1,request2,request3,])
      .then(values =>console.log(values))
      .catch(errs=>{
        console.log('catch======>',errs) // catch======> 系統(tǒng)故障
    })

Promise 的理解到此為止,但promise還不是'回調(diào)問題'的最終解決方案,在es2017(es8)中提出 async/await方案下篇文章我們繼續(xù)探討。

參考文檔:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Using_promises
http://es6.ruanyifeng.com/#docs/promise

最后編輯于
?著作權(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ù)。

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