0

I am facing an issue in my Node.js code when handling asynchronous and synchronous code.

I am looping through an array with the high order function forEach, I am handling a number of different things within this loop, such as creating new arrays, setting variables for future use, etc.

With the asynchronous nature of this loop and dealing with database connection (which returns a promise, the reasoning for the async), I am loosing the values due to the synchronous code being run prior to this code.

The code is being ran when a post request is hit

See code below@

    portfolio_data.forEach(async (e) => {
        let true_date = formatDateToString(e.Date);
        let true_time = formatTimeToString(e.Date);

        if (first_transaction_date > true_date) {
            first_transaction_date = true_date;
        }

        user_data.push({
            user_id: userData[0].id,
            type: e.Action,
            name: e.Details,
            quantity: e.Quantity,
            total: e.Total || e.Value,
            date: new Date(),
        });

        let true_quantity = GetTrueQuantity(true_date, true_time, e.Quantity);
        let sql = "SELECT * FROM `lookups` WHERE display_name = ? ORDER BY id DESC LIMIT 1";
        let query = await database.query(sql, e.Details)
        let current_price = query.length > 0 ? query[0].current_price : 0

        if (total_share_held_back_months_values[e.Details]) {
            total_share_held_back_months = total_share_held_back_months_values[e.Details];
        } else {
            total_share_held_back_months = GetTotalShareHeldForUserMarketGraph(portfolio_data, e.Details, current_price);
            total_share_held_back_months_values[e.Details] = total_share_held_back_months;
        }

        current_shares_held = total_share_held_back_months["current_held"];
        BackMonthShareHeldValues[e.Details] = total_share_held_back_months["back_month_held"];

            });

When I console.log the BackMonthShareHeldValues, they are blank and empty

What exactly is the best way to handle this situation when is comes to synchronicity hell?

Many thanks in advance guys.

  • I'm sorry but this code is hard to understand. You should firstly try to refactor it and separate it into smaller functions. It's hard to understand for us what is going on. You can also simplify it with implementation details (like removing additional fields, that doesn't change anything), so it will be also easier to understand. – PatrykMilewski Oct 07 '20 at 10:36
  • Maybe you are looking for [Using async/await with a forEach loop](https://stackoverflow.com/q/37576685/218196) – Felix Kling Oct 07 '20 at 10:44
  • 2
    `forEach` doesn't await the callback function. User `for..of` instead – Christian Oct 07 '20 at 11:26
  • Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Liam Oct 13 '20 at 14:59

0 Answers0