我正在尝试使用fetch
API 和Promise.all
功能从 2 个 API 并行获取数据。预计当给定数组中的所有承诺都解析时,将执行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
也返回一个承诺,所以responses.map( res => res.json())
返回一个你需要等待的 Promise 数组
您也需要在responses.map( res => res.json())
周围使用Promise.all
Promise.all(fetchPromises)
.then( responses => Promise.all(responses.map( res => res.json())))
.then(result => {
console.dir(result);
// do something with results
});