2017-04-07 44 views
0

我想在async.parallel里面运行两个sequelize查询,然后我可以在回调中将它们传递给一个窗体(虽然窗体集成不在这里显示)。当我运行它时会返回results.animals,但results.zones是未定义的。使用。然后里面的异步并行

我可以从日志中看到,在async.parallel回调函数已经运行之后,它在最后运行Zone.findAll。如果我只在一个区域中进行sequelize调用,那么它可以工作,但不是在查询state.findOne然后Zone.findAll时。

任何想法为什么会发生这种情况?我认为async.parallel应该等待两个完成之前完成回来?

async.parallel({ 
     animals: function(callback) { 
        Animal.findAll().then(function(animalResult){ 
         console.log("animals result: " + JSON.stringify(animalResult)) 
         callback(null, animalResult); 
        }) 
       }, 
     zones: function(callback){ 
        State.findOne({ 
         where : { abbr : req.query.state.toUpperCase() } 
        }).then(function(state) { 
         console.log("State ID: " + JSON.stringify(state['id'])) 
         Zone.findAll({ 
          attributes: ['name'], 
          where: { StateId : state['id']} 
         }) 
        }).then(function(zoneResult) { 
         console.log("zones result: " + JSON.stringify(zoneResult)); 
         callback(null, zoneResult); 
        }); 
       } 
     }, function(err, results) { 
      if (err) { return next(err); } 
      console.log("Results in callback: " + JSON.stringify(results)); 
      res.send(results) 
     } 
    ); 

回答

0

如果你的目标是让两者的结果(或可能更多)在您的形式提供查询的同时,您可以通过以下方式使用Promise.join:

var Sequelize = require('sequelize'); 
var sequelize = new Sequelize(dbName, username, ...); 

var getAnimals = function(){ 
    return Animal.findAll({ where: { name: 'xyz' }}); 
} 

var getZones = function(){ 
    return State.findOne({ where: { abbr : req.query.state.toUpperCase() }}) 
     .then(function(state){ 
      return Zone.findAll({ where: { StateId : state['id']} }}); 
     }); 
} 

// now use Promise.join to execute the 2 functions concurrently and 
// have their result in the handler function 
sequelize.Promise.join(getAnimals(), getZones(), function(animals, zones){ 
    // animals and zones are sequelize instances 
    console.log(animals.someProperty); 
    console.log(zones.someProperty); 
    res.json({ animals: animals, zones: zones }); 
});