【问题标题】:Sequelize - How to execute queries in sequence?Sequelize - 如何按顺序执行查询?
【发布时间】:2017-03-17 16:14:20
【问题描述】:

我正在使用 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 查询。如何防止这种情况并让它按顺序执行查询?

【问题讨论】:

  • 简单 ... return Papers.findAll({ 假设 .findAll 返回一个承诺
  • 谢谢@JaromandaX ...我必须返回两个查询才能让它工作

标签: javascript mysql promise sequelize.js


【解决方案1】:

由于您使用的是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 方法并使用这两个结果。

【讨论】:

    猜你喜欢
    • 2020-04-11
    • 1970-01-01
    • 2014-05-07
    • 2014-03-05
    • 1970-01-01
    • 2017-04-13
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多