Recursive async function in JavaScript
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
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
});
});
}
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)))();