async+await異步操作

以往的異步操作,都是使用callback的方式去實現,例如setTimeout()函數,一旦互相依賴的事件多了,這種方式就很容易造成callback hell,不易讀,很不友好:

 

setTimeout(()=>{
  console.log(x)
  setTimeout(()=>{
    console.log(xx)
    setTimeout(()=>{
      console.log(xxx)
    },1)
  },1)
},1)

於是乎,又有了Promise對象,雖然在很大程度上讓代碼易讀性提高了,但是一旦依賴多的時候還是免俗不了層層的.then:

 

axios.get('xxx/xxx').then(res=>{
  return x
}).then(res=>{
  return xx
}).then(res=>{
  .......//不斷的嵌套
})

而ES2017新增async語法,就很好的優化了這一點:
比如在沒有使用async語法的時候,我們寫的異步函數是這樣的:

 

export function readMsg(from){
  return (dispatch,getState)=>{
    axios.post('/user/readmsg',{from}).then(res=>{
      const userid = getState().user._id
      if (res.status == 200 && res.data.code == 0) {
        dispatch(messageRead(from,userid,res.data.num))
      }
    })
  }
}

我們換成async語法對比看看:

 

export function readMsg(from){
  return async (dispatch,getState)=>{
    const res = await axios.post('/user/readmsg',{from})
    const userid = getState().user._id
    if (res.status == 200 && res.data.code == 0) {
      dispatch(messageRead(from,userid,res.data.num))
    }
  }
}

這樣一對比,看似修改的地方並不多,但是,實際上用的就是一種同步的書寫方式,我們能看到,這種方式,隱式的執行了異步操作,使用await來做異步的等待,這樣,無論你有幾個互相依賴的異步要依次執行,都可以寫的簡單易懂:

 

const res = await axios.post('/user/readmsg',{from})
const res1 = await axios.post('/user/xxxxx')
const res2 = await axios.post('/user/yyyyy')
console.log(res,res1,res2)//會等到所有的異步都執行完再執行

值得注意的是,asyncawait必須要一起使用。

有了這麼方便的語法,以後的異步函數,我覺得可以儘可能的用它來實現。



作者:IUVO
鏈接:https://www.jianshu.com/p/51b78cd5ba17
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章