19

I'm trying to write a recursive function using async/await in JavaScript. This is my code:

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))

But I have syntax error:

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

SyntaxError: Unexpected identifier
  • possible duplicate? https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout – Kevin B Sep 15 '17 at 19:13

3 Answers3

16

I'd write your code as follows:

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)))();
  • 2
    This is a much nicer way to write the code but it doesn't answer the question like @James answer. – Jake Jun 27 '18 at 07:16
8

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
        });
    });
}
James
  • 80,725
  • 18
  • 167
  • 237
1

let rec_value = await recursion(value-1)

You can only await within an async function thus the JS engine is unable to parse the code.

Instead modify the usage to below since a async function always returns a Promise.

recursion(value-1).then((value) => { console.log(value)})

Refer to detailed documentation here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function