JavaScript中的递归异步函数

7 javascript recursion asynchronous node.js async-await

我正在尝试使用JavaScript中的async/await编写递归函数.这是我的代码:

async function recursion(value) {
  return new Promise((fulfil, reject) => {
    setTimeout(()=> {
      if(value == 1) {
        fulfil(1)
      } else {
        let rec_value = await recursion(value-1)
        fulfil(value + rec_value)
      }
    }, 1000)
    })
}

console.log(await recursion(3))
Run Code Online (Sandbox Code Playgroud)

但我有语法错误:

let rec_value = await recursion(value-1)
                              ^^^^^^^^^

SyntaxError: Unexpected identifier
Run Code Online (Sandbox Code Playgroud)

小智 9

我会写你的代码如下:

const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));

async function recursion(value) {
  if (value === 0) return 0;

  await timeout(1000);
  return value + await recursion(value - 1);
}

(async () => console.log(await recursion(3)))();
Run Code Online (Sandbox Code Playgroud)

  • 这是编写代码的一种更好的方法,但它并没有像@James 的回答那样回答问题。 (2认同)

Jam*_*mes 5

You haven't declared your setTimeout handler as async therefore the compiler doesn't recognise the await keyword. From the looks of it you don't actually need it at the top level so you can update as:

function recursion(value) {
    return new Promise((resolve, reject) => {
        setTimeout(async () => {
            // use await keyword
        });
    });
}
Run Code Online (Sandbox Code Playgroud)