我正在使用 sequelize 3.24.3 连接到 MySQL 数据库。
我的要求是:执行查询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 完成后调用第二个“then” block ,然后执行 findAll 查询。我怎样才能防止这种情况发生并让它按顺序执行查询?
最佳答案
由于您使用的是 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.findOne
和 Papers.findAll
并且在它们都返回结果后它将调用 spread
方法结果。
关于javascript - Sequelize - 如何按顺序执行查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40412324/