【问题标题】:Is there a good way to Promise.all an array of objects which has a property as promise?有没有一种好方法来 Promise.all 一个具有 Promise 属性的对象数组?
【发布时间】:2018-01-13 13:05:44
【问题描述】:

如果我有一系列承诺,我可以简单地使用Promise.all 来等待它们。

但是当我有一个对象数组时,每个对象都有一些是承诺的属性,有没有好的方法来处理它?

例子:

const files=urlOfFiles.map(url=>({
  data: fetch(url).then(r=>r.blob()),
  name: url.split('/').pop()
}))
//what to do here to convert each file.data to blob?
//like Promise.all(files,'data') or something else

【问题讨论】:

    标签: javascript asynchronous promise


    【解决方案1】:

    您可以将数据映射到解析为对象的 Promise 数组,而不是将数据映射到对象数组:

    const promises = urlOfFiles
        .map(url => fetch(url)
            // r.blob() returns a promise, so resolve that first.
            .then(r => r.blob())
            // Wrap object in parentheses to tell the parser that it is an
            // object literal rather than a function body.
            .then(blob => ({
                data: blob,
                name: url.split('/').pop()
            })))
    
    Promise.all(promises).then(files => /* Use fetched files */)
    

    【讨论】:

    • 但是如果一个文件对象有多个promise的属性,我需要写一个嵌套回调吗?
    • 这肯定会让它变得更复杂。 Promise.all() 的数组可能有效(类似于此答案,但使用 Promise.all(...) 而不是 fetch(url))。
    【解决方案2】:

    试试这样的:

    const files = urlOfFiles.map(url=>
      fetch(url).then(r=> ({
        data: r.blob()
        name: url.split('/').pop()
      })
      ))
    Promise.all(files)
    

    【讨论】:

    • 与对另一个答案的评论相同:结果对象数组不会将 blob 作为数据,而是承诺。
    【解决方案3】:

    使用返回值的多个异步属性,您可以使用嵌套的 Promise.all(如果其他异步结果依赖于 fetch 的响应)或按照 Tulir 的建议;从Promise.all([fetch(url),other])...开始:

    Promise.all(
      urlOfFiles.map(
        url=>
          fetch(url)
          .then(
            r=>
              Promise.all([//return multiple async and sync results
                r.blob(),
                Promise.resolve("Other async"),
                url.split('/').pop()
              ])
          )
          .then(
            ([data,other,name])=>({//return the object
              data,
              other,
              name
            })
          )
      )
    )
    .then(
      files=>
        console.log("files:",files)
    );
    

    【讨论】:

      猜你喜欢
      • 2013-01-09
      • 2020-08-31
      • 1970-01-01
      • 2022-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      • 1970-01-01
      相关资源
      最近更新 更多