簡體   English   中英

是否有一個很好的方法Promise.all一個具有承諾屬性的對象數組?

[英]Is there a good way to Promise.all an array of objects which has a property as promise?

如果我有一系列的承諾,我可以簡單地使用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

您可以將數據映射到解析為對象的promises數組,而不是將數據映射到對象數組:

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 */)

嘗試這樣的事情:

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

使用返回值的多個異步屬性,您可以使用嵌套的Promise.all (如果其他異步結果依賴於fetch響應)或者像Tulir建議的那樣; Promise.all([fetch(url),other])...開始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)
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM