Sequelize——如何按顺序执行查询

Sequelize - How to execute queries in sequence?

本文关键字:执行 查询 顺序 何按 Sequelize      更新时间:2023-09-26

我正在使用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"块,然后执行findAll查询。我怎么能防止这种情况,并有它的查询执行顺序?

既然您使用的是Sequelize,那么您也使用了bluebird。

您可以使用.all收集方法,由库提供。在文档中阅读更多信息。

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方法。