a have a little problem with recursive function that return promises:
function like this:
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("result");
}, 500);
});
let count = 1;
const recursiveWithPromise = () => {
return promise.then(result => {
count = 1
if (count !== 10) {
return recursiveWithPromise();
}
if (count === 10) {
return 'finalResult'
}
});
}
let a = recursiveWithPromise()
I want to save only finalResult in some variable, but if i save it like this:
const someVar = recursiveWithPromise(params)
or const someVar = recursiveWithPromise(params).then(res => res)
it was undefined. So how i can get my finalResult ?
CodePudding user response:
You are currently not returning the result of the recursive call. If you do, the last frame result will be returned back and forth to the first frame and will eventually get you the desired result:
return recursive(newParams);
Indeed, the return value of a Promise
callback can either be a bare value, or a Promise
which is automatically being unwrapped.
CodePudding user response:
Avoid using global state, especially with asynchronous programs. Instead write functions that accept arguments and return values -
function sleep(ms) {
return new Promise(r => setTimeout(r, ms))
}
function count(n) {
console.log(n)
if (n >= 10)
return "done"
else
return sleep(1000).then(_ => count(n 1))
}
count(0).then(console.log, console.error)
0
1
2
...
9
10
done
The beauty of async
/await
is that your asynchronous programs can look/feel nearly identical to their synchronous counterparts -
function sleep(ms) {
return new Promise(r => setTimeout(r, ms))
}
async function count(n) {
console.log(n)
if (n >= 10) return "done"
await sleep(1000)
return count(n 1)
}
count(0).then(console.log, console.error)
0
1
2
...
9
10
done
If your recursive function expects a promise as input, the program changes slightly -
function sleep(ms) {
return new Promise(r => setTimeout(r, ms))
}
function count(p) {
return p.then(n => {
console.log(n)
if (n >= 10)
return "done"
else
return count(sleep(1000).then(_ => n 1))
})
}
count(Promise.resolve(0)).then(console.log, console.error)
0
1
2
...
9
10
done
Again, using async
and await
improves the readability of the program significantly -
function sleep(ms) {
return new Promise(r => setTimeout(r, ms))
}
async function count(p) {
const n = await p
console.log(n)
if (n >= 10) return "done"
await sleep(1000)
return count(n 1)
}
count(Promise.resolve(0)).then(console.log, console.error)
0
1
2
...
9
10
done