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.