0

I notice that the next instruction of the for loop does not wait until for loop finish execution only execute that instruction. Besides that, I have followed some internet resources implement promise in my code but it still does not work as I expected.

The expected flow should be below:

  1. For loop each data that taken from wltInfo.
  2. Check if wltInfo.paymentMethod === null, it should execute the next subquery sequelize execution.
  3. Therefore, append merchant into the original json object.
  4. Remove the paymentMethod json keypair from the original json object.
  5. Print the response to the API caller.

Below is my code.

exports.retrieveAllTransactionByAccountOwner = async function (req, res) {
    try {
        const wthInfo = await WalletTransactionHistory.findAll({
            where: {},
            order: [["createdAt", "DESC"]],
            raw: true
        });
        arr = [];
       var ls = wthInfo.filter(async history => {
            parseObj = history;
            if (history.paymentMethod === null) {
                await db.sequelize.query("SELECT U.name AS name FROM OrderItemTransactions AS OIT INNER JOIN OrderItems AS OI ON OIT.itemId = OI.id INNER JOIN Orders AS O ON OI.orderId = O.id INNER JOIN RestaurantBranches AS RB ON O.branchNo = RB.id INNER JOIN Users AS U ON RB.restaurantId = U.id WHERE OIT.wthid = '" + history.id + "'", { type: db.sequelize.QueryTypes.SELECT }).then(restaurantInfo => {
                    if (restaurantInfo.length > 0) {
                        console.log(restaurantInfo[0].name);
                        parseObj.merchant = restaurantInfo[0].name;
                        arr.push(parseObj);
                        console.log(arr);
                    }
                    else {
                        arr.push(parseObj);
                    }
                });
            }
            else {
                arr.push(parseObj);
            }
        }).then(()=>{
            console.log("we are here");
            res.status(200).send({ transaction: arr });
        });
    }
    catch (err) {
        res.status(500).send({ error: err.message });
    }
}

I really appreciate u guys contribution because I have been stucking this issue been 1 week..

0 Answers0