如何用setTimeout()实现同步执行?

事情起源于一个延迟机制,大致意思是:当程序运行时,需要延迟运行一部分代码,如:延迟1秒执行。直接使用setTimeout():

async function doDelay() {
    const newUserId = 123
    return newUserId
}


let userId = 0
userId = setTimeout(function () {doDelay()}, 1000)
console.log('userId:', userId)

这个时候,程序运行下来,userId打印仍出来为0。原因是setTimeout()并没有使程序等待doRetry()的执行,setTimeout()本身是一个异步的。

改进方法:
function delay() {
    return new Promise(async function (resolve, reject) {
        async function doDelay() {
            const newUserId = 123
            resolve(newUserId)
            return
        }
        setTimeout(function () { doDelay()}, 1000)
    })
}


let userId = 0
await delay()
    .then(
        function resolveResult(newUserId) {
            userId = newUserId
         }
    )
console.log('userId:', userId)

程序运行:userId打印为123

重试:其实此方式通常被用来做重试:
function retry(fn, args, timer) {
  return new Promise(async function (resolve, reject) {
    async function doRetry() {
      if (timer > 0){
        timer--
        const newUserInfo = await fn(args)
    
        if (newUserInfo.length === 0) {
          setTimeout(function () {doRetry()}, 1000)
        } else{
          const userId = newUserInfo[0].user_id
          resolve(userId)
          return
        }
      } else {
        reject()
      }
    }
    doRetry()
  })
}

async function getUserId(userName) {
  let result = []
  await testDB.transaction(async trx => {
    result = await trx('t_user').select('user_id').where({ name: userName })
  })
  return result
}

主程序:
let userId = 0
// 重试三次getUserId()
await retry(getUserId, userName, 3)
    .then(
        function resolveResult(newUserId) {
            userId = newUserId
         },
        function rejectResult() {
                    throw new Error('获取新userId失败')
         }
    )
console.log('userId:', userId)

这样:retry,console.log('userId:', userId)就会同步执行
参考:https://www.thinbug.com/q/43363385

你可能感兴趣的:(如何用setTimeout()实现同步执行?)