Search code examples
node.jsexpressasync-awaitnode-fetch

Foreach and push() with async await doesn't push the values


Here's my code:

app.get("/bots/:id", async (req, res)=>{
 var bot = await Bots.findOne({id: req.params.id});
 if(!bot) return await res.send("not there");
 bot.desc = await marked(bot.desc);
 var user = req.user;
 bot.owner = [];
 await bot.owners.forEach(async (id)=>{
  await fetch(`${process.env.DOMAIN}/api/client/users/${id}`).then(r=>r.json()).then(async d=>{
  await bot.owner.push(d.tag);
 });
 });
 await console.log(bot.owner);
 await res.render('botpage.ejs', {user, bot});
})

App is express, fetch is node-fetch and I'm using ejs to render. When I do console.log(bot.owner), it logs [] and not the array of d.tags that I fetch. Everything is fine except this, including my api and ejs page. process.env.DOMAIN = https://discord.rovelstars.com


Solution

  • foreach loop not wait. use for loop instead of foreach.

    for(int i=0;i<bot.owners.length();i++){
     ....your task
    }
    

    or

    for(var obj of bot.owners){
     ...your task
    }
    

    visit this for more details