2016-11-03 66 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與兩個結果。