Tech:- Node, Express, Mongoose
1 - In an Api, I fetched all the documents from a mongoDB collection.which gives result as data(array) 2 - In each element of data done an async operation(Promise) 3 - consoled the data, got the result as expected ** 4 - but in response.send({data}) ** giving empty objects. 5 - If there is no async in map operation, Iam getting everything perfectly
await clientsOfSeller
.find()
.then(async (result) => {
let data = result.map( async someFunction);
Promise.all(data).then(() => {
console.log(data); // showing output
res
.status(200)
.send({
data, // getting empty objects
});
});
})
CodePudding user response:
You're adding the data
variable to the response but data
is simply the list of promises you created. It doesn't magically turn into a list of results after the promises resolve.
The response data gets turned into a JSON using the JSON.stringify()
function. A Promise
stringifies to an empty object, that's why you get empty objects in the response.
What you actually want to include in the response are the resolved results of the promises, which you get as the first argument to the callback method you pass to the .then()
method of Promise.all()
.
Change that part of your code into this:
Promise.all(data).then((results) => {
console.log(results);
res
.status(200)
.send({
status: 200,
message: "success",
data: results,
});
});