在蓝鸟承诺内执行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'); }); }); });
- 包含在可返回的生成器中的nodejs child_process.spawnSync或child_process.spawn返回输出
- 在Nodejs中使用asynchronous等待redis和bluebird
- 创build一个支持callback和承诺的Mongoose插件
- function类似Promise.some /任何未知数量的承诺
- nodejs – 帮助“promisifying”使用嵌套promise读取的文件
- 用蓝鸟提升Nodemailer?
- 与Bluebird手动promisifying pg.connect
- 未定义的Restify返回值不是错误对象中的函数
- 处理成功的HTTP承诺,如果一个蓝鸟失败