简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM