Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 611
3142 maple Avatar asked Jan 13 '18 13:01

3142 maple


2 Answers

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 */)
like image 99
Tulir Avatar answered Nov 14 '22 21:11

Tulir


Try something like this:

const files = urlOfFiles.map(url=>
  fetch(url).then(r=> ({
    data: r.blob()
    name: url.split('/').pop()
  })
  ))
Promise.all(files)
like image 43
kharandziuk Avatar answered Nov 14 '22 21:11

kharandziuk