我正在尝试使用fetchAPI 和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 也只有在给定数组中的所有 promise 都被解析时才会被解析。因此,在第二个回调函数中,then应该作为来自 API 的响应数组产生。
但是,我在控制台中得到的结果是:
result
(2) [Promise, Promise]
0: Promise
[[PromiseStatus]]: "pending",
[[PromiseValue]]: undefined
__proto__: Promise
1: Promise {<pending>}
length: 2
即未解决/未决的承诺被传递给回调。
我想我可能在这里遗漏了一个关于Promise.all功能的关键点。这种行为背后的原因是什么?
ibeautiful
相关分类