Recursive async function in JavaScript

20,227

Solution 1

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

Solution 2

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

Share:
20,227
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    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