Dawn
Dawn

Reputation: 303

Equivalent of async.map in new ES6?

Is there a way to use the new "async" javascript keyword to replace async.map from the async module? Basically I want to avoid using the async module if possible. For example, read many files at once, then do something when all the files have been read.

Upvotes: 0

Views: 1979

Answers (2)

Craig Myles
Craig Myles

Reputation: 5464

Helper function:

async function asyncMap(array, callback) {
  let results = [];
  for (let index = 0; index < array.length; index++) {
    const result = await callback(array[index], index, array);
    results.push(result);
  }
  return results;
}

Sample usage:

const titles = await asyncMap([1, 2, 3], async number => {
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/todos/${number}`
  );
  const json = await response.json();
  return json.title;
});

Inspired by this async forEach

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237875

Yes, generally you can do this with Promise.all.

let urls = [...];

let promises = urls.map(function(url) {
    return fetch(url).then(result => result.json()); // or whatever
});

Promise.all(promises).then(function(results) {
    // deal with the results as you wish
});

Or, to do it in a one-liner:

Promise.all(urls.map(url => fetch(url).then(res => res.json()))).then(function(results) {
    // deal with the results as you wish
});

Though that ain't easy to read, I fear...

It's not quite as sleek as async.map, though of course writing an appropriate wrapper would not be hard.

Upvotes: 3

Related Questions