async await函数和setTimeout套用问题

场景

async await函数是generator函数的语法糖,可以看作是以同步的语法执行异步语句,解决了连续调用promise导致的回调地狱问题。

一般工作中,我们往往在需要连续请求接口时使用async await语法糖。但是如果第二个要调用的接口需要延迟执行呢,很多同学就不知道怎么办了,甚至只能被迫改回.then嵌套的格式。

普通写法

不用async await的一般写法:

init(){
  axios.get('xxxx').then(res => {
    if(res.code === 0){
       setTimeout(() => {
         axios.get('xxxx').then(res => {
           //最终的处理
         }
       },1000)
    }
  })
}

可以看到,不用async await语法糖,真是老奶奶穿棉裤,一套又一套,可读性非常差。

解决方案

直接先上代码

错误代码:


async init(){
  try {
    let count = 0
    const res = await axios.get('xxxx')
    console.log('1')
    count ++ 
    setTimeout(async () => { 
      const res2 = await axios.get('xxx')
      console.log('2')
      count ++ 
    })
    console.log('3')
    console.log('count':count)
  }catch(err){}
}

//打印输出  1  3  count:1 2

正确代码:


async init(){
  try {
    let count = 0
    const res = await axios.get('xxxx')
    console.log('1')
    count ++
    const res2 = await new Promise(async function (resolve, reject) {
      console.log('2')
      setTimeout(async () => { 
        const res3 = await axios.get('xxx')
        console.log('3')
        count ++ 
        resolve(res3)
      })
    })
    count ++
    console.log('4')
    console.log('count:',count)
    if(res2.code === 0){
      //最后的处理
    }
  }catch(err){}
}

//打印输入。1  2  3  4   count:3

注意点:

  • 因为setTimeout的回调函数是异步执行的,所以我们要将其用promise包装下,这样就可以控制住setTimeout在async await函数主体中同步执行
  • 因为我们要在setTimeout内部继续发请求,所以其回调函数前也要加async

猜你喜欢

转载自blog.csdn.net/qq_38974163/article/details/128421125
今日推荐