[英]How to return promise.map (bluebird) inside a promise chain?
I'm using a chain to control flow and can't get promise.map in step2()
to wait until all of it's generated promises are resolved. 我正在使用链来控制流程,并且无法在
step2()
获取promise.map,直到所有生成的promise被解决为止。
Here's a visual of the flow I'm trying to achieve. 这是我要实现的流程的视觉效果。
step1() step2() step2() step2() step2() step3()
In step2()
I'm using Bluebird's promise.map. 在
step2()
我正在使用Bluebird的promise.map。
Here's the chain: 这是链:
step1()
.then(function() { return step2() })
.then(function() { return step3() })
.catch(function() { // handle errors })
Here's my functions for each step: 这是我每个步骤的功能:
let step1 = function() {
return new Promise(function(resolve, reject) {
// do stuff
resolve()
})
}
let step2 = function() {
return new Promise(function(resolve, reject) {
things = []
return Promise.map(things, function(thing) {
// load file async with callback
})
resolve()
})
}
let step3 = function() {
return new Promise(function(resolve, reject) {
// do stuff
resolve()
})
}
I've tested the chain with many more steps each with a timeout
and it worked as expected with the exception of the promise.map in step2()
. 我已经对链进行了更多的测试,每个步骤都有一个
timeout
并且它按预期工作,但step2()
中的promise.map例外。 What am I doing wrong? 我究竟做错了什么? :)
:)
The problem is from step 2. Promise.map
already return promise, so you can just return it to callee. 问题出在步骤
Promise.map
已经返回了promise,因此您可以将其返回给被调用者。 Then you warp the async function with callback with new Promise
. 然后,使用
new Promise
通过回调使异步函数变形。
let step2 = function() {
things = []
return Promise.map(things, function(thing) {
// load file async with callback
return new Promise(function(resolve, reject) {
fileAsyncFunc(thing, function callback(err, data) {
if(err) {
reject(err);
return;
}
resolve(data);
});
});
});
}
You are not calling your resolve
callback properly. 您没有正确调用您的
resolve
回调。
let step2 = function() {
things = []
return Promise.map(things, function(thing) {
return new Promise( function( resolve, reject ) {
// load file async with callback
resolve(...)
} )
})
}
In your case resolve()
is always called, since you are executing async function for loading the file. 在您的情况下,始终会调用
resolve()
,因为您正在执行异步功能以加载文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.