我正在尝试使用asynс/ await函数中的递归。问题是我无法在main函数中得到最终的承诺,我最初调用了递归方法
async function delay(ms) {
return await new Promise(resolve => setTimeout(resolve, ms))
}
async function recursion(i) {
return new Promise(async (resolve, reject) => {
if (i == 0) {
console.log(`i == 0`)
resolve(i)
} else {
console.log(`i = ${i}. Wait 1 second...`)
i--
await delay(2000)
await recursion(i)
}
})
}
async function main() {
let i = await recursion(3)
console.log(`END OF RECURSION`) //This code never use!
console.log(`i => ${i}`)
}
main()
的console.log:
i = 3. Wait 1 second...
i = 2. Wait 1 second...
i = 1. Wait 1 second...
i == 0
这是承诺建筑反模式。已经存在链条的承诺,无需创建新的链条。从Promise
回调返回的承诺被忽略,这打破了承诺链。此外,存在不一致性,该值并非总是从recursion
返回。
它应该是:
async function recursion(i) {
if (i == 0) {
console.log(`i == 0`)
return i
} else {
console.log(`i = ${i}. Wait 1 second...`)
i--
await delay(2000)
return recursion(i)
}
}