Sails JS - Nested .query method doesn't run sequence

148 views Asked by At

I beginner in Sails JS. I try to make multiple .query("SELECT ... "). I have a problem when looks like it not run sequence. I will explain my problem, look to My snippet code :

var isSuccess = true;
for(var loc = 0 ; loc < decode.length ; loc++){
    Location.query('SELECT * FROM abc', function (err, res){
      if (err) {
        isSuccess = false;
        return res.json(200, {
          data: {

          },
          status: {
            id: 0,
            message: err.message
          }
        });
      } else {
        var validate = res.rows;
        sails.log(validate);

      secondQuery.query('SELECT * FROM def', function (err, seconResult) {
        if (err) {
          isSuccess = false;
          sails.log("Update is Success : "+isSuccess);
          return res.json(200, {
            data: {

            },
            status: {
              id: 0,
              message: err.message
            }
          });
        } else {


        }
      });
      }
    });

    if(isSuccess){
      return res.json(200, {
        data: {

        },
        status: {
          id: 1,
          message: "Successful",
          isSuccess: isSuccess
        }
      });
    }
  }

When i request the API via POST method and the result is :

On Console Node JS Server :

Update is Success : false So it means the request is failed and must be return status = 0 in postman

But in the Postman, it show :

  data: {

        },
        status: {
          id: 1,
          message: "Successful",
          isSuccess: true
        }

My Question :

Can anyone help me to explain why and how to make it a sequence process, not like "multi thread" ? (In my case, i need to use RAW query cause i will face with really complex query)

Thank you.

1

There are 1 answers

2
Martial On BEST ANSWER

A for loop is synchronous while Location.query() method is not. So if you want to do it in sequence, you'll have to use Bluebird Promise.

Example (not tested) :

const Bluebird = require('bluebird');

const promises = [];
for(let loc = 0 ; loc < decode.length ; loc++) {
  promises.push(Location.query('SELECT ...'));
}

Bluebird.each(promises, (result) => res.json(200, {/* your payload data */}))
        .catch((err) => res.json(200, {/* your error data */}));

NB : Be careful when you use res variable in your callbacks when you use it in Sails controllers.