Reputation: 246
I have an issue with Node Async Await and recursive functions. For some reason, the code execution stops after resolving the Promise for a recursive function. Below is just a simple example I put in to demonstrate my issue (though found the problem while sending some requests with requests library).
If you run the code, you will see
Starting
Inside Promise
but not "Test Completed".
function promiseFunc(number) {
return new Promise((resolve, reject) => {
if (number == 100) {
console.log('Inside Promise');
resolve('Done');
} else {
number += 1
promiseFunc(number);
}
})
}
(async function testFunc() {
console.log('Starting');
await promiseFunc(0)
console.log("Test completed");
})()
Could someone please advise what is the issue?
Thank you in advance.
Upvotes: 0
Views: 71
Reputation: 26861
Here are some ways to fix it:
function promiseFunc(number) {
return new Promise((resolve, reject) => {
if (number == 100) {
console.log('Inside Promise');
resolve('Done');
} else {
number += 1;
resolve(promiseFunc(number));
}
})
}
(async function testFunc() {
console.log('Starting');
await promiseFunc(0)
console.log("Test completed");
})()
Or, interestingly enough, the equivalent code that uses async
/await
instead of explicit new Promise(...)
, works for your case:
// an async function returns a Promise
async function promiseFunc(number) {
if (number == 100) {
console.log('Inside Promise');
return 'Done';
} else {
number += 1;
// it seems to work as intended without saying return promiseFunc(...)
promiseFunc(number);
}
}
(async function testFunc() {
console.log('Starting');
await promiseFunc(0)
console.log("Test completed");
})()
Upvotes: 2
Reputation: 488
You have to do like this
function promiseFunc(number) {
return new Promise((resolve, reject) => {
http.post('/api')
.then((data) => {
resolve(data);
})
})
}
(async function testFunc() {
console.log('Starting');
const result = [];
for (let index = 0; index < 100; index++) {
result[index] = await promiseFunc(0);
}
console.log("Test completed");
})()
Upvotes: -1