d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Javascript Recursive Async Function
Add Reply New Topic New Poll
Member
Posts: 5
Joined: Jul 11 2022
Gold: 0.00
Jul 14 2022 08:29am
I'm attempting to compose a recursive function using async/await in JavaScript. This is my code:

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 This error:

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

SyntaxError: Unexpected identifier


Can someone guide me to what's the mistake in my code?
Thanks in advance!!
Member
Posts: 2
Joined: Jul 14 2022
Gold: 0.00
Jul 15 2022 04:13pm
You need to make your callbacks async as well, like
Code
setTimeout(async () => {

and
Code
return new Promise(async (fulfill, reject) => {
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll