async+await

最早的的使用异步操作的时候,我们一般会用setTimeout,会出现回掉地狱的情况

  1. setTimeout(()=>{
  2. setTimeout(()=>{
  3. setTimeout(()=>{
  4. console.log('1')
  5. },1000)
  6. },1000)
  7. },1000)

ES6中Promise

  1. //promise
  2. ()=>{
  3. axios.post('/user/readmsg',{from})
  4. .then(res=>{
  5. const userid = getState().user._id
  6. if( res.status === 200 && res.data.code === 0){
  7. dispatch(msgRead({userid,from,num:res.data.num}))
  8. }
  9. })
  10. }

ES7 async+await

  1. async ()=>{
  2. const res = await axios.post('/user/readmsg',{from})
  3. const userid = getState().user._id
  4. if( res.status === 200 && res.data.code === 0){
  5. dispatch(msgRead({userid,from,num:res.data.num}))
  6. }
  7. }