I got this API controler:
exports.doctorsList = async (req, res) => {
const users = await User.find().exec();
let responseArray = await users.map(async (user) => {
const transaction = await MedicalConsultation.find({
doctorOwner: user._id,
}).exec();
let cpLength = transaction.length;
return await {
_id: user._id,
name: user.name,
email: user.email,
specialty: user.specialty,
role: user.role,
createdAt: user.createdAt,
c_p: cpLength,
status: user.status,
};
});
console.log(responseArray);
res.json(responseArray);
};
In the console.log I got:
[ Promise { <pending> }, Promise { <pending> }, Promise
{ <pending> } ]
How is the correct way to write that code? or how to obtain the values?
users.map(async function(){... })
results in an array of promises, you need to await Promise.all(...)
on that array of promises.
So instead of:
let responseArray = await users.map(async (user) => {
// your code goes here
});
You need to:
let responseArray = await Promise.all(users.map(async (user) => {
// your code goes here
}));
If you're using bluebird, you can have a slightly nicer API.
const Promise = require('bluebird');
let responseArray = await Promise.map(users, async (user) => {
// your code goes here
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.