0

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

mamroure
  • 45
  • 6
  • 3
    jquery.each is like array.forEach in that respect - so, https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop/37576787#37576787 applies - with 2700 upvotes on that answer, I think it should help you realise what is wrong with your code – Bravo Dec 03 '20 at 23:17
  • 3
    How does this even not throw, when you use `await` in a non-async arrow function? – ASDFGerte Dec 03 '20 at 23:20
  • @Bravo yes i kept searching and nothing came up thnax – mamroure Dec 03 '20 at 23:21

0 Answers0