异步/等待中的递归无法在主要功能中解决

时间:2019-04-19 08:24:30

标签: node.js async-await es6-promise

我正在尝试使用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

1 个答案:

答案 0 :(得分:2)

这是承诺构造反模式。已经存在连锁的承诺,而无需创建新的。从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)
    }
}