node.js + bluebird:解析promise.all
我有一个函数requestJSON
查询外部API并返回(蓝鸟)承诺。
问题:b
在c
添加到列表之前得到解决,因此promise.all
运行,而a
和b
只被解析。
码:
let promises = [];
// push promise a
promises.push(requestJSON(..));
// push promise b
promises.push(requestJSON(..).then((response) {
// push promise c
promises.push(requestJSON({foo: response.bar});
});
promises.all((data) => {
console.log(data.length) // --> 2
});
回答如下:
你必须从.then
回调中返回一些东西。如果你想继续等待别的东西,要么是价值(然后是承诺被认为已经解决),要么是另一个承诺。
let promises = [
requestJSON(/* [1] */),
requestJSON(/* [2] */).then(response => {
return requestJSON(/* [3] */);
})
];
// this waits for [1] and [3]
promises.all(promises).then(results => {
console.log(data.length);
});
你的代码没有从.then()
返回任何内容。所以函数返回值是undefined
,并且使用undefined
作为结果确定了promise。
以上内容可以写成(注意箭头函数中没有完整体的隐式return
):
let promises = [
requestJSON(/* [1] */),
requestJSON(/* [2] */).then(response => requestJSON(/* [3] */))
];
promises.all(promises).then(results => console.log(data.length));
评论列表(0)
- 暂无评论