如何通过Bluebirds .map传输一些数据?
我使用Blubird和Sequelize(使用Blubird)。
假设我有一个类似于以下的代码:
Feed.findAll() .map(function (feed) { // <---- this is what I'm interested in below // do some stuff here return some_promise_here; }) .map(function (whatever) { // What is the best way to access feed here? }) ....
我发现了一些暗示可能的解决办法的答复,但我不能完全明白这一点。
我曾尝试Promise.all()
.spread()
,但我从来没有设法使其工作。
Feed.findAll() .map(function (feed) { // <---- this is what I'm interested in below // do some stuff here return some_promise_here.then(function(result){ return { result: result, feed: feed};// return everything you need for the next promise map below. }); }) .map(function (whatever) { // here you are dealing with the mapped results from the previous .map // whatever -> {result: [Object],feed:[Object]} })
这看起来非常类似于如何在.then()链中访问以前的承诺结果? ,但是你正在处理一个.map
调用,似乎想要访问处理数组的相同索引的前一个结果。 在这种情况下,并不是所有的解决scheme都适用, 封闭似乎是最简单的解决scheme:
Feed.findAll().map(function (feed) { // do some stuff here return some_promise_here.then(function (whatever) { // access `feed` here }); })
不过,您也可以应用显式传递 ,就像@ bluetoft的答案中所述。