An array of promises with results separately

Basically, I'm looking for something like Promise.all(), but one that calls a function in then()for each result, as soon as this result is ready. It's trivial to write using standard callbacks like this (file reading example):

function foo(files, bar) {
  for (let file of files) {
    const fr = new FileReader();
    fr.onload = e => bar(e.target.result);
    fr.readAsDataURL(file);
  }
}

I am sure there is a library there that does what I want, but I would like to do it in pure JS.

To clarify, I would like to have something like this:

function foo(files) {
  // do something here;
}

foo(['1','2','3']).then(/* do something here with separate results */);`
+4
source share
2 answers

Just use map:

let read = file => return new Promise(resolve => {
  const fr = new FileReader();
  fr.onload = e => resolve(e.target.result);
  fr.readAsDataURL(file);
});

Promise.all(files.map(file => read(file).then(bar)))
  .then(allResultsFromBar => { /* use results array */ });

, .then -, , (.. Promise.resolve), Promise.all promises , bar .

+5

@jib :

readFiles, , , - , then() on, , ( ) .

, .then() , , Promise.all().

:

let read = file => return new Promise((resolve, reject) => {
    const fr = new FileReader();
    fr.onload = e => resolve(e.target.result);
    fr.onerror = reject; // don't forget to reject on error
    fr.readAsDataURL(file);
});

let readFiles = files => return Promise.all(files.map(read)); // <<<<< this is the line you seek

:

const files = ["...", "...", "..."];
readFiles(files)
.then(allFileResults => allFileResults.map(bar)); // bar is your function for processing file results
// possibly chain another .then() if required to observe/process bar() results

, bar() .

, , :

  • " " ; allFileContents.map(bar) Promise.all(), , bar().
  • readFiles(...) ( - ) scupper ; allFileContents.map(bar) ; ; , .
  • , bar() ; , Promise.all(), .. allFileResults => Promise.all(allFileResults.map(bar)).

@jib , , , .

0

All Articles