我正在使用蓝鸟承诺在Node.js工作。我想在我的承诺链中使用Promise.all,并尝试了这个:
request-promise(some_API_call)
.then( (responseBody) => {
// using responseBody to determine N new API calls to make
var arrayPromises = [];
for (var i=0 ; i<N ; i++) {
var newPromise = request-promise(new_API_call_i);
arrayPromises.push(newPromise);
}
return(arrayPromises);
})
.all(arrayPromises)
.then( (arrayResults) => {
// do something
});
给我一个错误:arrayPromises is undefined
。
我能想到的另一种方式是:
request-promise(some_API_call)
.then( (responseBody) => {
// using responseBody to determine N new API calls to make
var arrayPromises = [];
for (var i=0 ; i<N ; i++) {
var newPromise = request-promise(new_API_call_i);
arrayPromises.push(newPromise);
}
Promise.all(arrayPromises)
.then( (arrayResults) => {
// do something
});
})
我想知道是否:
答案 0 :(得分:2)
arrayPromises
未定义,因为它是在以下then
无法访问的回调范围内定义的。我想您希望从最初的Promise.all
返回then
并从那里继续链接:
request-promise(some_API_call)
.then( (responseBody) => {
// using responseBody to determine N new API calls to make
var arrayPromises = [];
for (var i=0 ; i<N ; i++) {
var newPromise = request-promise(new_API_call_i);
arrayPromises.push(newPromise);
}
return Promise.all(arrayPromises);
})
.then( (arrayResults) => {
// do something
});