2016-11-03 119 views
2

我使用sequelize 3.24.3连接到MySQL数据库。Sequelize - 如何按顺序执行查询?

我的要求是:执行查询1,然后在查询1完成后执行查询2。下面是代码样品

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); 
}); 

当上述运行:findOne完成后,它调用第二“然后”块和之后执行的findAll查询。我怎样才能防止这种情况,并让它顺序执行查询?

+0

简单...'Returns Papers.findAll({'承担'.findAll'返回一个承诺 –

+0

谢谢@JaromandaX ...我必须返回两个查询才能使其工作 –

回答

0

由于您使用Sequelize您还正在使用bluebird

您可以使用.all收集方法,由库提供。阅读更多关于它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); 
}); 

这将执行Student.findOnePapers.findAll在一起,之后他们都返回结果,它会调用该方法spread与两个结果。