微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

forEach 中的推送对象在地图查看端为空

如何解决forEach 中的推送对象在地图查看端为空

我希望从 forEarch 中推送对象,在获取 forEarch 内部的数据后,console.log 会向我显示正确的值,并且对象已正确推送到数组中。

但是在forEach的最后,如果我尝试访问推送的对象,数组中没有对象

下面的代码

async function get_line_items(items) {
              
            line_items2 = [];

            await items.forEach((element,index) => {

                const id = element.id;
            
                if (id) {

                    await getPriceFromCartCheckout(id,(err,results) => {
                        if (err) {
                            console.log(err);
                            return;
                        }

                        if (results && !isEmpty(results)) {
                            // Add new item
                            line_items2.push({
                                name: element.name,amount: results[0].price,currency: "eur",quantity: element.quantity,})

                        }
                        console.log(line_items2) // => Here objects are properly added to the array on each loop
                    });
                }

            })
            console.log(line_items2) // => Here the array is empty.
            return line_items2;
          }

          const line_items = await get_line_items(req.body[1].items);

          console.log( line_items); // => Here the array is empty.


module.exports = {
getPriceFromCartCheckout: async (id) => {

        return await pool.query(`SELECT volume,price FROM products WHERE id = ?`,[ 
            parseInt(id)
        ])
        .then(iuidtest => {
            return iuidtest;
        });
    },};

任何帮助将不胜感激:)

在这里找到解决方案:

NodeJS async MySQL call to connection pool returns no result

解决方法

您应该等待 getProductIdWeightPrice 而不是循环本身。循环做它应该做的 - 循环数组,调用一些外部方法。这些方法做什么 - 循环不关心。

为了“暂停”循环,您需要等待异步调用以获取数据。这样做,它会起作用:)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。