我正在尝试使用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功能的关键点。这种行为背后的原因是什么?
1 回答
ibeautiful
TA贡献1993条经验 获得超5个赞
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
});
添加回答
举报
0/150
提交
取消