简体   繁体   English

为什么我在同一个块中得到不同的数组值?

[英]why am i getting different array values in the same block?

i'm using node.js as an api to my app.我使用 node.js 作为我的应用程序的 api。 the thing is in this block of code i'm editing the values of the arrays inside a forEach loop but when i console.log() them i'm still getting the empty arrays.事情是在这段代码中,我正在 forEach 循环中编辑数组的值,但是当我使用 console.log() 它们时,我仍然得到空数组。 i'm thinking that the forEach loop is getting executed after the console.log() in POSITION 2 and after the response being sent.我在想 forEach 循环是在 POSITION 2 中的 console.log() 之后和发送响应之后执行的。 and just for the record, in POSITION 1 i'm getting the right values as i want只是为了记录,在 POSITION 1 我得到了我想要的正确值

here's the code这是代码

router.post('/', (req, res, next) => {
    userId = req.body.userId;

    sqlQuery = `SELECT mealsids FROM tmporders WHERE userid = ${userId}`;

    con.query(sqlQuery, function (err, rows) {
        let mealsIds = [];
        let mealsNames = [];
        let mealsPrices = [];
        let mealsImages = [];
        var index = 0

        if (rows['rows'].length > 0) {
            mealsIds = rows['rows'];

            mealsIds[0]['mealsids'].forEach((row) => {

                sqlQuery2 = `SELECT name, image, price FROM meals WHERE id = ${mealsIds[0]['mealsids'][index]}`;

                con.query(sqlQuery2, function (err, rows) {
                    if (err) {
                        console.log('Failed BITCH');
                        res.sendStatus(202)
                    } else {
                        mealsNames.push(rows['rows'][0]['name']);
                        mealsPrices.push(rows['rows'][0]['price']);
                        mealsImages.push(rows['rows'][0]['image']);

                        /*   POSITION 1   */
                        console.log('============POSITION 1============');
                        console.log(mealsNames);
                        console.log(mealsPrices);
                        console.log(mealsImages);

                        /*  END OF POSITION 1   */
                    }
                });
            });

            /*   POSITION 2   */
            console.log('============POSITION 2============');
            console.log(mealsNames);
            console.log(mealsPrices);
            console.log(mealsImages);

            /*  END OF POSITION 2   */


            res.json({
                statusCode: 201,
                count: mealsNames.length,
                mealsIds: mealsIds,
                mealsNames: mealsNames,
                mealsImages: mealsImages,
                mealsPrices: mealsPrices
            })

        } else {
            console.error("Failure");
            console.log(err);
            res.sendStatus(202);
        }
    });
});

is there any way to fix this logical error?有什么办法可以解决这个逻辑错误吗?

Try this, it can make errors to your code, but still you can develop your code better by following this pattern.试试这个,它可能会使您的代码出错,但您仍然可以通过遵循此模式更好地开发代码。

const Query = conn => query => new Promise((resolve, reject) => {
  try {
    conn.query(query, (err, res) => {
      if (err) return reject(err)
      resolve(res.rows)
    })
  } catch (er) {
    reject(er)
  }
})

router.post('/', async (req, res, next) => {
  try {
    const query = Query(con);

    userId = req.body.userId;

    const rows = await query(`SELECT mealsids FROM tmporders WHERE userid = ${userId}`)

    if (!rows.length) {
      return res.status(202).json({
        message: '0 rows'
      })
    }

    console.log({ rows })

    mealsIds = rows.rows;

    console.log({ mealsIds })

    const meals = await mealsIds[0].mealsids.reduce((promise, e) => promise.then(async acc => {
      const currentResult = await query(`SELECT name, image, price FROM meals WHERE id = ${mealsIds[0].mealsids[0]}`)

      return acc.concat(currentResult[0])
    }), Promise.resolve([]))

    console.log({ meals })

    res.status(200).json({
      meals
    })

  } catch (err) {
    res.status(500).json(err)
  }
});

BTW, your node version has to be higher than 8.0 to run this code.顺便说一句,您的节点版本必须高于 8.0 才能运行此代码。 Try node -v in the terminal.在终端中尝试node -v

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM