【问题标题】:Promise.all results are as expected, but individual items showing undefinedPromise.all 结果符合预期,但个别项目显示未定义
【发布时间】:2019-07-18 23:34:10
【问题描述】:

首先,Google Chrome 中的 console.log 存在一些问题,无法按预期运行。这不是我在 VSCode 中工作的情况。

  1. 我们从对服务器的两个 async 调用开始。

    promise_a = fetch(url)
    promise_b = fetch(url)
    
  2. 由于 fetch 结果也是承诺,因此需要在每个项目上调用 .json()。正如 Stackoverflow 用户所建议的那样,将使用辅助函数 process - 抱歉丢失了链接。

        let promiseResults = []

        let process = prom => {
            prom.then(data => {
               promiseResults.push(data);
            });
         };
  1. Promise.all 被调用。结果数组被传递给 .then,其中 forEach 每次迭代都会在 item.json() 上调用 process 并将履行的承诺推送到 promiseResults
        Promise.all([promise_a, promise_b])
          .then(responseArr => {
             responseArr.forEach(item => {
               process(item.json());
             });
          })              
  1. 没有为最终的 .then 块提供参数,因为 promiseResults 在外部范围内。 console.log 显示令人困惑的结果。

    .then(() => {
    console.log(promiseResults); // correct results
    console.log(promiseResults[0]); // undefined ?!?
    })
    

任何帮助将不胜感激。

【问题讨论】:

标签: javascript promise fetch


【解决方案1】:

如果您熟悉 async/await 语法,我建议您不要使用外部变量 promiseResults,而是使用此函数即时返回结果:

async function getJsonResults(promisesArr) {
    // Get fetch promises response
    const results = await Promise.all(promisesArr); 

    // Get JSON from each response promise
    const jsonResults = await Promise.all(results.map(r => r.json()));
    return jsonResults
}

这是用法示例:

promise_a = fetch(url1)
promise_b = fetch(url2)

getJsonResults([promise_a, promise_b])
   .then(theResults => console.log('All results:', theResults))

使用theResults 变量提取必要的结果。

【讨论】:

  • 太棒了!很高兴能提供帮助;)
【解决方案2】:

你可以试试这个,它看起来数组循环在 Promise 环境中运行不正常。 具体来说:promiseResults 在您登录后填充。

var resultAll = Promise.all([promise_a, promise_b])
  .then(responseArr => {
     return Promise.all(responseArr.map(item => return item.json()));
  });

resultAll.then(promiseResults => {
   console.log(promiseResults);
});

【讨论】:

  • 我觉得应该是Promise.all(responseArr.map(item => process(item.json())))
  • 你应该是正确的方法,没有尝试我写的但是,Promise.all 也将通常的数组作为可迭代的,不需要是承诺数组。
  • 这个解决方案也有效,我喜欢两次使用 Promise.all 的简单性。推送到外部阵列是错误的方法。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-02
  • 2019-04-05
  • 2022-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多