云计算

【React.js 22】async+await异步操作

2018-04-24  本文已影响2041人  IUVO

ES2017新增async语法,用一种很优雅的方式去实现了异步操作,具体讲解可以参照阮一峰大神的文章

以往的异步操作,都是使用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必须要一起使用。

有了这么方便的语法,以后的异步函数,我觉得可以尽可能的用它来实现。

上一篇 下一篇

猜你喜欢

热点阅读