【问题标题】:.then Executes on 'pending' Rather than Resolved Promise.then 在“未决”而不是已解决的承诺上执行
【发布时间】:2017-02-22 03:18:49
【问题描述】:

为什么下面的代码会记录一组待处理的 Promise?我希望数组中的所有承诺都得到解决,然后执行 .then 方法中的函数。

for (let i = 0; i < limit; i++) {
    promiseArray.push(fetch(someUrls[i]))
}

Promise.all(promiseArray)
    .then(responses => responses.map(response => response.text()))
    .then(result => console.log(result))

提前致谢

【问题讨论】:

    标签: javascript arrays es6-promise


    【解决方案1】:

    那是因为response.text() method returns a promisefetch 是一个 2-promise 的东西。一个用于实际请求,另一个用于转换。

    您可以做的是将array.map 操作包装在另一个Promise.all 中。

    Promise.all(promiseArray)
        .then(responses => Promise.all(responses.map(response => response.text())))
        .then(result => console.log(result))
    

    【讨论】:

      【解决方案2】:

      您还需要将链式 then 放入 Promise.all 中,因为 response.text() 也会返回另一个承诺。

      for (let i = 0; i < limit; i++) {
          promiseArray.push(fetch(someUrls[i]))
      }
      
      Promise.all(promiseArray)
          .then(responses => Promise.all(responses.map(response => response.text()))) //Needs to wait for all text() promise methods to resolve
          .then(result => console.log(result))
      

      或者你可以在你的 for 循环中链接承诺:

      for (let i = 0; i < limit; i++) {
          promiseArray.push(fetch(someUrls[i]).then(res => res.text()));
      }
      
      Promise.all(promiseArray).then(result => console.log(result))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-02-21
        • 2017-06-06
        • 1970-01-01
        • 2023-03-15
        • 2018-04-02
        • 2020-03-16
        • 2016-01-10
        相关资源
        最近更新 更多