0

I'm looking to push object from a forEarch, after getting data inside forEarch, the console.log show me correct value and object are properly pushed to the array.

But at the end of the forEach, if I try to access to the object pushed, there is no object inside the array

Code below

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;
        });
    },
};

Any help would be appreciate :)

Found the solution here :

NodeJS async MySQL call to connection pool returns no result

seserize
  • 99
  • 3
  • 8
  • It's not "at the end". You don't wait for the `getProductIdWeight` callbacks. You should make this function return a promise so that you can cleanly await for it. – Denys Séguret May 31 '21 at 11:35

1 Answers1

1

You should await getProductIdWeightPrice and not the loop itself. The loop does what it's supposed to do - looping the array, calling some external methods. What those methods do - the loop does not care.

In order to "pause" the loop, you need to await the async call to get the data. Do that and it will work :)

Andrey Popov
  • 7,362
  • 4
  • 38
  • 58
  • I just updated the code to use async/await with getPriceFromCartCheckout but now its telling me : await getProductIdWeightPrice(id, (err, results) => { ^^^^^ SyntaxError: await is only valid in async function – seserize May 31 '21 at 11:59
  • That's great, but now `getPriceFromCartCheckout ` is **awaiting** for the query. Basically what that function returns is the **result** of the db query. And that result is NOT a Promise (or async function call). You can simply do something like: `getPriceFromCartCheckout: async (id) => pool.query(\`SELECT volume, price FROM products WHERE id = ?\`, [ parseInt(id)])` It will work IF `pool.query` returns a promise/async function. – Andrey Popov May 31 '21 at 12:09
  • I updated it to this: https://pastebin.com/7euj7jX1 But I still have the same error "await is only valid in async function" – seserize May 31 '21 at 12:17
  • You need to either use short return `async (id) => pool.query` (meaning this function will return the call of pool.query), or return it explicitly in the function body: `async (id) => { return pool.query }`. You now execute a function, which calls pool.query, but returns void. – Andrey Popov May 31 '21 at 13:35