【问题标题】:Foreach and push() with async await doesn't push the values带有异步等待的 Foreach 和 push() 不会推送值
【发布时间】:2021-07-12 01:21:22
【问题描述】:

这是我的代码:

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 是 express,fetch 是 node-fetch,我使用 ejs 来渲染。 当我执行 console.log(bot.owner) 时,它会记录 [] 而不是我获取的 d.tags 数组。 除了这个,一切都很好,包括我的 api 和 ejs 页面。 process.env.DOMAIN = https://discord.rovelstars.com

【问题讨论】:

    标签: node.js express async-await node-fetch


    【解决方案1】:

    foreach 循环不等待。使用 for 循环而不是 foreach。

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

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

    访问this了解更多详情

    【讨论】:

    • 它应该是 for....of 而不是 for....in,for...in 用于对象迭代
    猜你喜欢
    • 2019-06-29
    • 2019-01-15
    • 2017-10-29
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多