猿问

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

我正在尝试使用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功能的关键点。这种行为背后的原因是什么?


当年话下
浏览 116回答 1
1回答

ibeautiful

res.json也返回一个 Promise,所以responses.map( res => res.json())返回一个你需要等待的 Promise 数组您需要使用Promise.all周围responses.map( res => res.json())太Promise.all(fetchPromises)&nbsp; &nbsp; .then( responses => Promise.all(responses.map( res => res.json())))&nbsp; &nbsp; .then(result => {&nbsp; &nbsp; &nbsp; console.dir(result);&nbsp; &nbsp; &nbsp; // do something with results&nbsp; &nbsp; });
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答