Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  70] [ 7]  / answers: 1 / hits: 29994  / 7 Years ago, fri, september 15, 2017, 12:00:00

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

More From » node.js

 Answers
17

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




[#56469] Wednesday, September 13, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nikoguym

Total Points: 339
Total Questions: 106
Total Answers: 95

Location: Mali
Member since Sat, Feb 12, 2022
2 Years ago
;