在蓝鸟承诺内执行asynchronous操作

所以,我一直在殴打这个几天,我很难解决什么是最好的解决办法。 我正在使用HAPI的Waterline / dogwater,并试图做一些大致的事情:

wardrobe.find({WardrobeId: 5}).then(function(clothes) { //got my clothes in my wardrobe. clothes.find({Type: 'trousers'},{Kind: 'nice ones'}).then(function(trousers) { //got my nice trousers _.each(trousers, function(trouser) { //logic to see if these are my pink trousers console.log('color?', trouser.color); }); console.log('ding'); }); }); 

我遇到的麻烦是代码在输出裤子颜色之前总是会ding 。 这是因为,尽我所知, _.each将使代码asynchronous。 我试图介绍承诺(蓝鸟),但没有运气。 我甚至看过发生器(Co),但是我的节点版本在v0.11之前是固定的。

我想在_.each执行一些数据库查询,将这些结果(如果有的话)返回给裤子对象,然后返回:

 wardrobe.find({WardrobeId: 5}).then(function(clothes) { //got my clothes in my wardrobe. clothes.find({Type: 'trousers'},{Kind: 'nice ones'}).then(function(trousers) { //got my nice trousers _.each(trousers, function(trouser) { //logic to see if these are my pink trousers db.colors.find({Color: trouser.color}).then(function(color) { //color here? }); }); console.log('ding'); }); }); 

什么是尽可能有效地做到这一点的最好方法?

帮助表示赞赏。 很高兴回到这里,并把重点放在需要的地方。

那么_.each人都与不同步无关。 这只是一个下划线/ lodash的方式做trousers.forEach(...) 。每个trousers.forEach(...)

你的问题是执行asynchronous操作的db.colors.find方法。 如果您希望它们按顺序执行,则可以链接这些方法:

 wardrobe.find({WardrobeId: 5}).then(function(clothes) { //got my clothes in my wardrobe. clothes.find({Type: 'trousers'},{Kind: 'nice ones'}).then(function(trousers) { //got my nice trousers var p = Promise.resolve(); _.each(trousers, function(trouser) { //logic to see if these are my pink trousers p = p.then(function() { return db.colors.find({Color: trouser.color}) .then(function(color) { // color here, they'll execute one by one }); }); }); p.then(function(){ console.log('ding, this is the last one'); }); }); }); 

或者,如果你想让他们同时发生,而不是等待前一个:

 wardrobe.find({WardrobeId: 5}).then(function(clothes) { //got my clothes in my wardrobe. clothes.find({Type: 'trousers'},{Kind: 'nice ones'}).then(function(trousers) { //got my nice trousers Promise.map(trousers, function(trouser) { return db.colors.find({Color: trouser.color}); }).map(function(color){ console.log("color", color); }).then(function(){ console.log('ding, this is the last one'); }); }); });