简体   繁体   中英

If statement in nodejs not executing in order

Below is controller.js script. I am facing hard time to go inside if loop "if(changeUserToSellerFlag == 1)" because this if statement is executed much earlier than this if statement "if (results.Name == "Customer")". I am not sure why the order of execution is not done line by line.

const { updateUserSellerStatus } = require("./seller.model.js");

const { genSaltSync, hashSync } = require("bcrypt");
const userid = require("../auth/token_validation.js");
const {
  updateUserRoleAfterSellerApproval,
  getRoleName,
} = require("../users/user.service.js");

module.exports = {
  sellerVerify: (req, res) => {
    var sellerStatusName;
    var changeUserToSellerFlag = 0; // this flag determines if user to seller update is needed or not

    approvedByName = req.fullName; //get full name from token_validation.js
    approvedByEmail = req.email; //get email from token_validation.js
    console.log("Request body is below");
    console.log(req.body); // contains body sent by postman

    updateUserSellerStatus(
      req.body,
      approvedByName,
      approvedByEmail,
      (err, results) => {
        if (err) {
          console.log(err);
          return res.status(500).json({
            success: 0,
            message: err,
          });
        }
        if (!results) {
          console.log(results);
          return res.json({
            success: 0,
            message: err,
          });
        }

        if (req.body.sellerStatus == 3) {
          sellerStatusName = "Rejected";
        } else if (req.body.sellerStatus == 2) {
          sellerStatusName = "Completed";
        } else if (req.body.sellerStatus == 1) {
          sellerStatusName = "Pending";
        }
        //verify if user is a seller or not
        if (req.userId) {
          getRoleName(req.userId, (err, results) => {
            console.log("check rolename gettign below");
            console.log(results);
            if (results.Name == "Customer") {
              console.log("User is Customer");
              changeUserToSellerFlag = 1;
              console.log("flag is :" + changeUserToSellerFlag);
            } else if (results.Name == "Seller") {
              console.log("User is Seller");
              changeUserToSellerFlag = 0;
            }
            if (err) {
              console.log(err);
              return res.status(500).json({
                success: 0,
                message: err,
              });
            }
          });
        }

        console.log("see flag changed here ", changeUserToSellerFlag);
        if (changeUserToSellerFlag == 1) {
          console.log("i am here");
          //update userrole to seller only if user is not a seller earlier
          updateUserRoleAfterSellerApproval(
            req.userId,
            req.roleId,
            (err, results) => {
              console.log("result details are bwlo");
              console.log(results);
              if (err) {
                console.log(err);
                return res.status(500).json({
                  success: 0,
                  message: err,
                });
              }
              if (!results) {
                console.log(results);
                return res.json({
                  success: 0,
                  message: err,
                });
              }
              console.log("Update into UserRole Completed successfully");
            },
          );
        } else {
          console.log(
            "User is already a seller and dont need to update userrole table",
          );
        }

        console.log(sellerStatusName);
        return res.status(200).json({
          success: 1,
          status: sellerStatusName,
        });
      },
    );
  },
};

Below is console output

Request body is below
{ sellerId: 122, sellerStatus: 2 }
see flag changed here  0
User is already a seller and dont need to update userrole table
Completed
check rolename gettign below
TextRow { Name: 'Customer', RoleId: 2 }
User is Customer
flag is :1

where "User is already a seller and dont need to update userrole table" is executed first before "flag is:1"

to me it looks as if you're treating asynchronous code as if it was synchronous. At the top of the function you are calling parts of the code that are asynchronous, like for example every database query is generally async call.

getRoleName(req.userId, (err, results) //i assume this is an async call

process will not wait for the above code to finish before proceeding forward with its execution because it is written synchronously. So next instructions that it will execute are:

console.log('see flag changed here ', changeUserToSellerFlag);//0
if(changeUserToSellerFlag == 1)//0 --> false
}else{console.log("User is already a seller and dont need to update userrole table");}//so these 3 orders are executed immediately.

after which the async call from (i assume)

getRoleName(req.userId, (err, results)

will have finished and the proper callback will be called.

as a potential solution: I would either wait for any database call to finish before proceeding. You can use async - await call, other solutions are also usage of Promises and of course making a callback hell.

If we use callback because you are already using them it would look something like this:

updateUserSellerStatus(
    req.body,
    approvedByName,
    approvedByEmail,
    (err, results) => {
        if (err) {
            console.log(err);
            return res.status(500).json({
                success: 0,
                message: err,
            });
        }
        if (!results) {
            console.log(results);
            return res.json({
                success: 0,
                message: err,
            });
        }

        if (req.body.sellerStatus == 3) {
            sellerStatusName = "Rejected";
        } else if (req.body.sellerStatus == 2) {
            sellerStatusName = "Completed";
        } else if (req.body.sellerStatus == 1) {
            sellerStatusName = "Pending";
        }
        //verify if user is a seller or not
        if (req.userId) {
            getRoleName(req.userId, (err, results) => {
                    console.log('check rolename gettign below');
                    console.log(results);
                    if (results.Name == "Customer") {
                        console.log("User is Customer");
                        changeUserToSellerFlag = 1;
                        console.log("flag is :" + changeUserToSellerFlag);
                    } else if (results.Name == "Seller") {
                        console.log("User is Seller");
                        changeUserToSellerFlag = 0;
                    }

                    console.log('see flag changed here ', changeUserToSellerFlag);
                    if (changeUserToSellerFlag == 1) {
                        console.log("i am here");
                        //update userrole to seller only if user is not a seller earlier
                        updateUserRoleAfterSellerApproval(
                            req.userId,
                            req.roleId,
                            (err, results) => {
                                console.log("result details are bwlo");
                                console.log(results);
                                if (err) {
                                    console.log(err);
                                    return res.status(500).json({
                                        success: 0,
                                        message: err,
                                    });
                                }
                                if (!results) {
                                    console.log(results);
                                    return res.json({
                                        success: 0,
                                        message: err,
                                    });
                                }
                                console.log("Update into UserRole Completed successfully");
                            }
                        );
                    } else {
                        console.log("User is already a seller and dont need to update userrole table");
                    }

                    console.log(sellerStatusName);
                    return res.status(200).json({
                        success: 1,
                        status: sellerStatusName,
                    });
                }


                if (err) {
                    console.log(err);
                    return res.status(500).json({
                        success: 0,
                        message: err,
                    });
                }
            });
    }
);
},
};

I just moved the code which was below the

console.log('see flag changed here ', changeUserToSellerFlag);

inside the first callback method.

I'd recommend refactoring the callback-hell asynchronicity to promises.

Happily, util.promisify in Node's util library makes it super easy to do that for functions that are callback-async.

You end up with something like this:

const { promisify } = require("util");
const { updateUserSellerStatus } = require("./seller.model.js");
const userid = require("../auth/token_validation.js");
const {
  updateUserRoleAfterSellerApproval,
  getRoleName,
} = require("../users/user.service.js");

const updateUserSellerStatusP = promisify(updateUserSellerStatus);
const getRoleNameP = promisify(getRoleName);
const updateUserRoleAfterSellerApprovalP = promisify(
  updateUserRoleAfterSellerApproval,
);

async function sellerVerify(req) {
  var sellerStatusName;
  var changeUserToSellerFlag = 0; // this flag determines if user to seller update is needed or not
  switch (req.body.sellerStatus) {
    case 3:
      sellerStatusName = "Rejected";
      break;
    case 2:
      sellerStatusName = "Completed";
      break;
    case 1:
      sellerStatusName = "Pending";
      break;
  }

  const results = await updateUserSellerStatusP(
    req.body,
    req.fullName,
    req.email,
  );
  if (!results) throw new Error("No results from UUSS");

  //verify if user is a seller or not
  if (req.userId) {
    const roleName = await getRoleNameP(req.userId);
    if (roleName.Name === "Customer") {
      changeUserToSellerFlag = 1;
    } else if (roleName.Name === "Seller") {
      changeUserToSellerFlag = 0;
    }
  }

  if (changeUserToSellerFlag) {
    console.log("i am here");
    //update userrole to seller only if user is not a seller earlier
    const results = await updateUserRoleAfterSellerApprovalP(
      req.userId,
      req.roleId,
    );
    console.log(results);
    if (!results) throw new Error("UURASP results missing");
    console.log("Update into UserRole Completed successfully");
  } else {
    console.log(
      "User is already a seller and dont need to update userrole table",
    );
  }

  console.log(sellerStatusName);
  return {
    success: 1,
    status: sellerStatusName,
  };
}

module.exports = {
  sellerVerify: async (req, res) => {
    try {
      const result = await sellerVerify(req);
      return res.json(result);
    } catch (err) {
      console.error(err);
      return res.status(500).json({
        success: 0,
        message: err,
      });
    }
  },
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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