admin管理员组

文章数量:1289583

If I have an array of promises, I can simply use Promise.all to wait for them all.

But when I have an array of objects, each of them having some properties that are promises, is there a good way to deal with it?

Example:

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

If I have an array of promises, I can simply use Promise.all to wait for them all.

But when I have an array of objects, each of them having some properties that are promises, is there a good way to deal with it?

Example:

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
Share Improve this question edited Jan 13, 2018 at 13:20 Ahmad Baktash Hayeri 5,8804 gold badges32 silver badges43 bronze badges asked Jan 13, 2018 at 13:05 3142 maple3142 maple 9072 gold badges11 silver badges29 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

Instead of mapping the data to an array of objects, you could map it to an array of promises that resolve to objects:

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

Try something like this:

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

With multiple async properties of the return value you could use nested Promise.all (if other async results rely on response of fetch) or as Tulir suggested; start off with a 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)
);

本文标签: