事情起源于一個(gè)延遲機(jī)制,大致意思是:當(dāng)程序運(yùn)行時(shí)劲适,需要延遲運(yùn)行一部分代碼楷掉,如:延遲1秒執(zhí)行。直接使用setTimeout():
async function doDelay() {
const newUserId = 123
return newUserId
}
let userId = 0
userId = setTimeout(function () {doDelay()}, 1000)
console.log('userId:', userId)
這個(gè)時(shí)候霞势,程序運(yùn)行下來(lái)烹植,userId打印仍出來(lái)為0。原因是setTimeout()并沒(méi)有使程序等待doRetry()的執(zhí)行愕贡,setTimeout()本身是一個(gè)異步的草雕。
改進(jìn)方法:
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)
程序運(yùn)行:userId打印為123
重試:其實(shí)此方式通常被用來(lái)做重試:
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)就會(huì)同步執(zhí)行
參考:https://www.thinbug.com/q/43363385