为什么Promise.all(..)在附加的处理程序中传递未解决/待处理的Promise?
我正在尝试使用fetch
API和Promise.all
功能从2个API并行获取数据。预期当解决给定数组中的所有promise时,将执行then
中的回调。但是我在回调函数中获得了未完成的承诺。
用于实现所需目标的功能代码
const fun = () => {
const fetchPromises = [
fetch('api-1'),
fetch('api-2')
];
Promise.all(fetchPromises)
.then( responses => responses.map( res => res.json()))
.then(result => {
console.dir(result);
// do something with results
});
}
我希望then
的回调函数仅在Promise.all被解析时才执行,而Promise.all仅在给定数组中所有应许都被解析时才被执行。因此,在第二个then
的回调函数中,结果应为来自API的响应数组。
但是我在控制台中得到的结果是:
result
(2) [Promise, Promise]
0: Promise
[[PromiseStatus]]: "pending",
[[PromiseValue]]: undefined
__proto__: Promise
1: Promise {<pending>}
length: 2
即,未解决/待处理的承诺被传递为回调。
我想我可能在这里缺少关于Promise.all
功能的要点。这种行为背后的原因是什么?
[res.json
也会返回Promise,所以responses.map( res => res.json())
返回的是您需要等待的Promise数组
您也需要在Promise.all
周围使用responses.map( res => res.json())
Promise.all(fetchPromises)
.then( responses => Promise.all(responses.map( res => res.json())))
.then(result => {
console.dir(result);
// do something with results
});