Async await function and setTimeout application problem

Scenes

The async await function is the syntactic sugar of the generator function, which can be regarded as executing asynchronous statements in a synchronous syntax, which solves the callback hell problem caused by continuous calls to promises.

In general work, we often use async await syntactic sugar when we need continuous request interfaces. But if the second interface to be called needs to be delayed, many students don't know what to do, and they can only be forced to change back to the nested format of .then.

common writing

General writing without async await:

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

It can be seen that without the syntactic sugar of async await, it is really a grandma wearing cotton trousers, one set after another, and the readability is very poor.

solution

directly on the code

error code:


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

Correct code:


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

important point:

  • Because the callback function of setTimeout is executed asynchronously, we need to wrap it with promise, so that we can control the synchronous execution of setTimeout in the body of the async await function
  • Because we want to continue sending requests inside setTimeout, we also need to add async before the callback function

Guess you like

Origin blog.csdn.net/qq_38974163/article/details/128421125