3

I'm using sequelize 3.24.3 to connect to a MySQL database.

My requirement is to: execute query 1 and then execute query 2 after query 1 completes. Below is the code sample

Student.findOne({
    where:{
        userID:request.query.userID
    }
}).then(function(data){
    Papers.findAll({
            where:{
                userID:request.query.userID
            }
        }
    )
}).then(function (papers) {
    response.json({success: true,  paper: papers,});
}).catch(function (err) {
    console.log(err);
});

When the above runs: after findOne completes it calls the second "then" block and afterwards executes the findAll query. How can I prevent this and have it the queries executed sequentially?

2
  • simple ... return Papers.findAll({ assuming .findAll returns a promise Commented Nov 3, 2016 at 23:55
  • Thanks @JaromandaX ... I had to return both queries to get it to work Commented Nov 4, 2016 at 1:28

1 Answer 1

1

Since you are using Sequelize you are also using bluebird.

You can use .all collection method, provided by the library. Read more about it in the documentation.

const Promise = require("bluebird");

Promise.all([
    Student.findOne({ where : { userID: request.query.userID } }),
    Papers.findAll({ where : { userID: request.query.userID } })
]).spread( function( student, papers ) {
    response.json({success: true,  paper: papers });
}).catch( function( error ) { 
    console.log(err);
});

This will execute Student.findOne and Papers.findAll together and after they both return results it will call the spread method with the two results.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.