为了账号安全,请及时绑定邮箱和手机立即绑定

为什么 Promise.all(..) 在附加的 then 处理程序中传递未解决/待处理的承诺?

为什么 Promise.all(..) 在附加的 then 处理程序中传递未解决/待处理的承诺?

当年话下 2021-11-12 16:38:34
我正在尝试使用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

    });


查看完整回答
反对 回复 2021-11-12
  • 1 回答
  • 0 关注
  • 111 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信