I'm not exactly sure what's happening or maybe my understanding of asynchronous functions is just bad.
I have two functions:
const retrieveConvosList=(username)=>{
return new Promise(async(resolve,reject)=>{
await userModel.findOne({username:username},async(error,foundUser)=>{
if(error) return reject(error);
resolve(await retrieveConvosListName(foundUser.convos,username));
})
})
}
and
const retrieveConvosListName=async(convoIDList,username)=>{
let convoListAndName = [];
convoIDList.forEach(async(convo)=> {
await messages.findById(convo,(error,foundConvo)=>{
if(error) console.log(error);
foundConvo.users.forEach(user => {
if(user != username){
const convoIndex = foundConvo.convoIndex;
const objLit = {};
objLit[convoIndex] = user;
convoListAndName.push(objLit);
}
});
})
});
return convoListAndName;
})
retrieveConvosList is called in one of my routes like this
renderOBJ.convoList = await roomUtilLib.retrieveConvosList(renderOBJ.user.username);
The problem is that my function retrieveConvosListName is returning the value of convoListAndName (which is an empty array that I assigned at the start of the function) before my callback of messages.findById completes.
I can't seem to understand it's behavior.