關於Promise的一些

github同步

1.定義

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

爲什麼要重新從定義回顧,是因爲我覺得就是因爲定義太過於簡單,所以細節容易被忽略。

比如怎麼纔算最終的狀態?怎麼更好的處理異常?如何兼容多個瀏覽器?

恰巧最近在整理項目代碼時,發現了Promise的一些小坑,特地重新回顧複習一遍,希望下面的介紹可以讓你有所收穫!

2.基礎用法


const timeDefer = milliseconds => new Promise(resolve => {
    setTimeout(() => {
       resolve() 
    }, milliseconds)
   }
)

這是一個簡單的用法,可以用來模擬異步請求。

假設用在類似React的組件中,異步請求回來後需要render部分UI,我們經常會在回調裏寫類似this.renderTable(response)處理邏輯。

那麼讓我們檢測下吧。


const timeDefer = milliseconds => new Promise(resolve => {
    console.log(this)
    setTimeout(() => {
      resolve() 
    }, milliseconds)
  }
)

timeDefer(1000).then(() => console.log('success'))

//undefined
//success

糟糕,在scope內拿不到this。

你也許會說你由於箭頭函數的問題,好,我們換爲ES5。


var hanlder = {
  method: function(milliseconds) {
    return function(resolve) {
      console.log(this)
      setTimeout(function(){
        resolve() 
      }, milliseconds)
    }
  }
}

function timeDefer(milliseconds) {    
  return new Promise(hanlder.method(milliseconds))
} 

timeDefer(1000).then(() => console.log('success'))

//undefined
//success

依然沒有獲取到,所以,這必須和箭頭函數無關。

注意:我的運行環境爲webpack編譯後的runtime上下文內。

再換一種思路試試吧。

<script>

const timeDefer = milliseconds => new Promise(resolve => {
    console.log(this)
    setTimeout(() => {
      resolve() 
    }, milliseconds)
  }
)

timeDefer(1000).then(() => console.log('success'))

</script>

//window
//success

如上,我直接寫在了頁面裏,結果是你想的嗎?

很驚奇吧!沒錯,Promise回調內的this是和上下文有關係的,不一定具體是什麼,但應該是global

3.簡單請求:fetch

我們經常會用一些fetch的庫,如whatwg-fetch,其實fetch就是基於Promise的一種實現,而許多瀏覽器也支持原生的fetch,如Chrome;同樣的,像IE這種非主流當然肯定是不支持的,所以這些庫往往會幫我們去做polyfill。

fetch請求資源的用法如下:


const getJSON = url => fetch(url)
      .then(response => response.json())


getJSON('/data.json')
  .then(json => console.log('success1', json))
  .catch(error => console.log('failed0'))

這裏唯一需要注意的一點就是response.json(),它返回的是一個Promise對象,請切記這一點。

對於Promise後面跟的鏈式thenable函數,一般有兩種寫法,上述等同於


getJSON('/data.json')
  .then((response, error) => {
      //do something
  })

第一首較第二種來說更加直觀清晰,所以大多數情況下都比較推薦第一種。

但第一種的寫法有一些規則需要注意:

  • 1.如果then後面接then,不管有多少個,只要請求是成功的,都會依次進入

getJSON('/data.json')
  .then(json => console.log('success1', json))
  .then(json => console.log('success1', json))
  .catch(error => console.log('failed0'))

//success1
//success1
  • 2.如果catch放在then後面並且請求失敗了,那麼then還是會進去

getJSON('/data.json')
  .catch(error => console.log('failed0'))
  .then(json => console.log('success1', json))

//failed0
//success, undefined

這種情況最容易犯錯,而且還不易排查,確保你的異常處理作爲鏈式收尾。

  • 3.服務器返回404

對於這個case,希望你可以先自己猜猜,在看輸出。


const getJSON = url => fetch(url)
      .then(response => {
          console.log('success0', response)
          return response.json()
      })
      .then(json => {
        console.log('success1', json)
      })
      .catch(error => {
        console.log('failed0')
      })


getJSON('/data1.json')//無效url,404

//success: 0
//failed0

你沒有看錯,對於fetch(尤其是使用原生)來說,404是‘成功‘的請求,並不會直接進catch。

類似的問題許多庫的issue裏都提到:Why both of then and catch are invoked when reponse status is 404

因此正確的處理應該是:


const getJSON = url => fetch(url)
      .then(response => {
        if (response.status === 200) {
          console.log('success0', response)
          return response.json()
        }
      })
      .then(json => {
        console.log('success1', json)
      })
      .catch(error => {
        console.log(error, 'failed0')
      })

4.高級用法:鏈式

Promise最大的作用就是解決了地獄回掉,並且給異步方法提供了優美的語法糖。

鏈式基本寫法:


const success = () => Promise.resolve({data: {}})

const failed = () => Promise.reject({error: {}})

success()
  .then(response => console.log(response))
  .catch(error => console.log(error))

success()
  .then((response, error) => {
    console.log(response, error)
  })

Promise.resolvePromise.reject分別返回一個已經成功/失敗的promise對象,我在此用來模擬成功/失敗的請求。

基於上面的回顧,幾個小demo可以用來檢測下自己對鏈式的掌握:

  • Demo1:

success('success0')
  .then(response => console.log(response))
  .then(response => console.log(response))
  .then(response => console.log(response))
  .then(response => console.log(response))

//success
//undefined
//undefined
//undefined

這個應該很好理解,我在上面已經提到了then的傳遞性

  • Demo2:

success('0')
  .then(response => {
    console.log('failed', response)
    failed(response)
  })
  .catch(error => {
    console.log('recovery', error)
    return success(error)
  })
  .then((response, error) => console.log(response, error))

// failed 0
// undefined, undefined

這個結果是不讓你懵逼了,如果是,那麼先看下個例子。


success('0')
  .then(response => {
    console.log('failed', response)
    return failed(response)
  })
  .catch(error => {
    console.log('recovery', error)
    return success(error)
  })
  .then((response, error) => console.log(response, error))

// failed 0
// recovery 0
// 0 undefined

沒錯,差別就在於一個return,也許你一個小的手誤就會導致一個大bug。

所以切記:如果在Promise的回掉邏輯裏依然是是Promise,且希望有鏈式的後續處理,記得一定要返回該實例。

有了上面的基本知識,我們用最後一個Demo來結束本文:

  • Demo3:

const getJSON = url => fetch(url)
  .then(response => response.json())//.json() will return a promise
  .catch(error => console.log(error))

假設getJSON('/data.json')會返回一個形如:


{
    urls: [
        'file1.md',
        'file2.md',
        'file3.md',
        ...
        'file12.md'
    ]
}

的json對象,包含接下來需要請求的資源。

我們在回調裏的實現方式如下:

1.


getJSON('/data.json')
  .then(data => {
    data.urls.forEach(url => {
      getJSON(url)
    });
  })

2.


getJSON('/data.json')
  .then(data => {
    let thenableRequest = Promise.resolve();
    data.urls.forEach(url => {
      thenableRequest.then(() => getJSON(url))
    });
  })

3.


getJSON('/data.json')
  .then(data => {
    let thenableRequest = Promise.resolve();
    data.urls.forEach(url => {
      thenableRequest = thenableRequest.then(() => getJSON(url))
    });
  })

等同於

getJSON('/data.json')
  .then(data => {
    data.urls.reduce(
      (thenable, url) => thenable.then(() => getJSON(url)),
       Promise.resolve()
      )
  })

如果你能一口氣說出其中的區別,或者告訴我Network中資源請求的順序,那麼請忽略本文。

第一種:

並行請求 ,但不能保證順序,所以結果不可預期,如果這不是請求資源,而是數個有依賴順序的API,那結果肯定不能滿足你。

第二種:

其實和第一種沒有太大區別,只是稍微用鏈式重構了下,但實質並沒有變。

第三種:

getJSON每次都會返回一個新的Promise對象,你可以將其看作是reduce的結果,這種鏈式最終的結果是串行請求所有資源,即先file1.md, file2.md, … file12.md,如果用Network去查看,可以發現它是依次請求的,保證的順序。

這三種方法其實就在解決一個問題,而也就是爲什麼有Promise.all的原因了。

Promise.all既做保證了順序也做了異常處理:所有的請求都成功了才能拿到最終結果,否者則會reject。

利用Promise.all改寫如下:


getJSON('/data.json')
  .then(data => Promise.all(data.urls.map(url => getJSON(url))))
  .then(responseArray => console.log('responseArray', responseArray))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章