Issue
I would like to know how I can set up my Express route to deliver the data back to the client when a recursive function is called with promises and fetching MongoDB data. What’s happening right now is that my route executes immediately, with the data never being sent back to the client. The data does come in but comes in after the data has been sent. Here’s my code that I’m working with:
const fetchTrees = (source, root) => {
return new Promise((resolve, reject) => {
User.find({referrer: source}).then((response) => {
for (person in response) {
const document = response[person]._id
root[document] = {
name: response[person].first_name + ' ' + response[person].last_name,
uppLine: response[person].uppLine,
_id: response[person]._id
}
const descendants = fetchTrees(document, root[document])
root[document].descendants = descendants
}
})
console.log("Hey", root)
if (root._id !== null || root._id !== undefined) {
resolve(root)
} else {
reject("No tree data")
}
})
}
fetchTrees(source, root).then((result) => {
console.log("Returnnn",result)
if (result) {
return res.status(200).send(result)
} else {
return res.status(404).send("No tree found")
}
})
"Hey" and "Returnnn" show up like this before the data even comes in:
Hey {}
Returnnn {}
Solution
It will help if you wait for this recursive async operation. Instead of getting the inner promise results immediately, you can use the "Promise.all" function to wait for operation completion.
Instead of for loop;
const promises = response.map((person) => {
const document = person._id;
root[document] = {
name: person.first_name + ' ' + person.last_name,
uppLine: person.uppLine,
_id: person._id,
};
return fetchTrees(document, root[document]);
});
And you can use these promises;
Promise.all(promises)
.then((results) => {
root[document].descendants = results;
console.log("Hey", root);
if (root._id !== null || root._id !== undefined) {
resolve(root);
} else {
reject("No tree data");
}
})
.catch((error) => {
reject(error);
});
Answered By – umutcakir
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0