最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Problem with asyncawait while using .forEach - Stack Overflow

programmeradmin1浏览0评论

I'm making a simple Redis' request which is supposed to return all VALUES (not keys) in my database. The problem is that my function returns tab before the .forEach even starts. Why do I know that? My console.log(tab)'s result is printed before console.log(cards) for each iteration. My interpreter also tells me inside the .forEach function that "Promise returned from forEach argument is ignored". What have I done wrong there? Why isn't async/await working inside .forEach?

router.get("/", async (req, res) => {
    try {
        const keys = await client.keys("*")
        //console.log(result)
        const tab = []
        await keys.forEach(async (key) => {
            const cards = await client.smembers(key)
            console.log(cards)
            tab.push(cards)
        })
        console.log(tab)
        return res.send(tab)
    } catch (err) {
        console.error(err)
    }

});

I'm making a simple Redis' request which is supposed to return all VALUES (not keys) in my database. The problem is that my function returns tab before the .forEach even starts. Why do I know that? My console.log(tab)'s result is printed before console.log(cards) for each iteration. My interpreter also tells me inside the .forEach function that "Promise returned from forEach argument is ignored". What have I done wrong there? Why isn't async/await working inside .forEach?

router.get("/", async (req, res) => {
    try {
        const keys = await client.keys("*")
        //console.log(result)
        const tab = []
        await keys.forEach(async (key) => {
            const cards = await client.smembers(key)
            console.log(cards)
            tab.push(cards)
        })
        console.log(tab)
        return res.send(tab)
    } catch (err) {
        console.error(err)
    }

});
Share Improve this question asked Nov 3, 2021 at 17:29 crazyfrogcrazyfrog 2471 gold badge5 silver badges13 bronze badges 3
  • forEach doesn't return a promise which is why you're getting that warning. – Andy Commented Nov 3, 2021 at 17:31
  • how about reduce or map? would it work with them? I'd like to avoid using loops – crazyfrog Commented Nov 3, 2021 at 17:37
  • You'll still be iterating over an array with map or reduce. Maybe create an array of promises and await Promise.all instead. – Andy Commented Nov 3, 2021 at 20:20
Add a ment  | 

1 Answer 1

Reset to default 7

forEach is not meant to work with async functions. You can use a for ... of loop instead.

for(const key of keys){
    const cards = await client.smembers(key)
    console.log(cards)
    tab.push(cards)
}
发布评论

评论列表(0)

  1. 暂无评论