when i put a promise in the loop the function returns an empty object when i take it out it works fine
const getAllMessages = async () => {
try {
const html = await request.get(); // works fine
const $ = cheerio.load(html);
const messages = {};
$("").each((i, col) => {
let id;
let user;
let key;
// when i print these values here it works
let {text,token} = await readMessage(key);
//but the object isnt saved
messages[key] = {
user: user,
id: key,
text:text,
token:token,
}
})
// it logs {} when i put the await call in loop
//without the await in loop it works fine and returns the other values
console.log(messages);
return messages;
} catch (error) {
console.log(error);
}
};
here is the call
getAllMessages()
.then(messages => {
console.log("done");
console.log(messages);
})
.catch(err => console.log(err));
it resolves and wait for a bit to end the program ,it means the promises are still on the event loop but the promise resolves before is there a way to make it wait till all the promises in the loop are resolved