I have an async
function that needs to return an array of user_ids. My code is like:
async function getUserIds(option) {
let user_ids = [];
if (option === 'test') {
const departments = await Departments.find({}).exec()
.catch(() => console.log('ERROR');
console.log('BEFORE LOOP');
await departments.forEach(async(dpt) => {
const pop = await Populations.findOne({_id: dpt.id})
.catch(() => console.log('ERROR');
console.log('work...');
if (pop && (pop.max > pop.min)) {
const _users = await User.find({_id: {$in: pop.ids}}).exec()
.catch(() => console.log("ERROR");
user_ids = user_ids.concat(_users.map((u) => u._id));
console.log('finished work...');
}
});
return user_ids;
}
async function main() {
let user_ids = await getUserIds('test');
console.log(user_ids);
}
Now this is always returning an empty array []
and I can see the console logs in an asynchronous way:
BEFORE LOOP
[] --> the return
work...
work...
work...
work...
work...
work...
finished work...
finished work...
work...
finished work...
work...
finished work...
finished work...
I guess this line await departments.forEach(async(dpt) => {
is not really "awaiting"
so what can I do, what I'm doing wrong ?