How to use the each function from async

Find comprehensive JavaScript async.each code examples handpicked from public code repositorys.

async.each is a method in the Async library for Node.js that runs an asynchronous function for each element of an array or object, handling the results and errors appropriately.

160
161
162
163
164
165
166
167
168
169
 * Manually collect all missing prerequisites
 * Therefore we do not pass error to async-callbacks as this would exit the process
 */
function checkDependencies(checks, callback) {
  let hasErrored = false;
  async.each(
    checks,
    function (check, cb) {
      check.call(this, function (error, warning) {
        if (error) {
fork icon268
star icon0
watch icon1

1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
  // the array index to match up the basic and detailed results.
  ...(idx < detailedSubmissionResult.rowCount
    ? detailedSubmissionResult.rows[idx]
    : {}),
}));
await async.each(locals.submissions, async (s) => {
  if (s.feedback?.manual) {
    s.feedback_manual_html = await markdown.processContent(
      s.feedback.manual.toString() || ''
    );
fork icon251
star icon248
watch icon14

How does async.each work?

async.each is an async utility function in the async library for iterating over a collection of elements, executing an asynchronous function for each element in the collection, and then calling a final callback function once all iterations are complete. It is similar to the Array.prototype.forEach method, but designed to work with asynchronous functions.

80
81
82
83
84
85
86
87
88
89
            `${basePath}/topic` :
            `${basePath}/consumers/${groupId}`);
}

initZkPaths(cb) {
    async.each([this.getBucketsZkPath()],
               (path, done) => this._zkClient.mkdirp(path, done), cb);
}

_processBucket(ownerId, bucketName, done) {
fork icon18
star icon0
watch icon1

207
208
209
210
211
212
213
214
215
  var oldpath = path.join(LOCAL_CACHE_DIR, zipFilename);
  extractZip(oldpath, { dir: destinationDir, defaultFileMode: parseInt('744', 8) }, cb);
}


async.each(remappedUrls, function (urlObject, cb) {
  if (!urlObject || !urlObject.url || !urlObject.component) {
    return cb();
  }
fork icon17
star icon128
watch icon0

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const async = require("async");

const items = ["item1", "item2", "item3"];

async.each(
  items,
  function (item, callback) {
    console.log("Working on " + item);
    callback(); // Make sure to call the callback when done
  },
  function (err) {
    if (err) {
      console.log("Error: " + err);
    } else {
      console.log("All items have been processed successfully");
    }
  }
);

In this example, we have an array of items and we want to process them asynchronously. We use async.each to iterate over each item and process them. The second argument is the function to be called for each item. It takes two arguments, the item itself and a callback function that needs to be called when the processing is done for that item. The third argument is a callback function that is called once all items have been processed or if an error occurs during the processing.

86
87
88
89
90
91
92
93
94
95
if (err) return callback(err);
const list = [];
for (let i = 0; i < result.length; i++) {
  list.push(result[i]);
}
async.each(list, function(item, cb) {
  item.calculateDerived(req.user, function(err) {
    if (err) return cb(err);
    userMentions += calculateUnreadMessages(item._userMention, req.user.OSMUser);
    mainLangMentions += calculateUnreadMessages(item._mainLangMention, req.user.OSMUser);
fork icon10
star icon27
watch icon6

37
38
39
40
41
42
43
44
45
46
async.parallel([
  function(callback) {
    userModule.find(query, sort, function(err, result) {
      if (err) return callback(err);
      users = result;
      async.each(users, function (item, eachcb) {
        item.calculateChanges(eachcb);
      }, function(err) {
        if (req.query.sort === "OSMBC-changes") {
          users.sort(function(b, a) { return a._countChanges - b._countChanges; });
fork icon10
star icon27
watch icon6

822
823
824
825
826
827
828
829
830
831

//if(!task.deps_config) return cb(); //just in case?
if(!task.config) return cb(); 

//normal apps should have _inputs (validator doesn't)
async.each(task.config._inputs, (input, next_dep)=>{
    if(!input.task_id) return next_dep(); //old task didn't have this set?
    load_task(input.task_id, (err, dep_task)=>{
        if(err) return next_dep(err);
        //process uses app-stage to load input datasets
fork icon9
star icon8
watch icon0

+ 2 other calls in file

17
18
19
20
21
22
23
24
25
26
```c
var async = require('async');
var fs = require('fs');

fs.readdir('./bufferconcat', function (err, files) {
  async.each(files, function (file, callback) {
    if( file.length > 32 ) {
      console.log('This file name is too long');
      callback('File name too long');
    } else {
fork icon1
star icon8
watch icon3

1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
    calllback(err);
} else {
    console.log("gots " + scenes.length + " scenes");
    var availableScenes = [];
    availableScenesResponse.availableScenes = availableScenes;
        async.each(scenes, function (scene, cb) {
            availableScene = {};
            if (scene.scenePostcards != null && scene.scenePostcards.length > 0) { //cain't show without no postcard
                var postcardIndex = Math.floor(Math.random()*scene.scenePostcards.length);
                var oo_id = ObjectID(scene.scenePostcards[postcardIndex]); //TODO randomize? or ensure latest?  or use assigned default?
fork icon1
star icon3
watch icon2

+ 15 other calls in file

55
56
57
58
59
60
61
62
63
64
    })
  })
}
async each(coll, iteratee) {    
  return new Promise(async (resolve, reject) => { 
    async.each(coll, iteratee, (err, res) => {
      if (err) { 
        reject(err)
      } else {
        resolve(res)
fork icon1
star icon0
watch icon1

+ 21 other calls in file

726
727
728
729
730
731
732
733
734
735
if (err) {
    return cb(err);
} else {
    const fileNames = {};
    const reverseMap = {};
    return async.each(
        verilogEntries,
        function (entry, callback) {
            //fileName = shortid.generate() + '_' + Date.now() + '.v'
            const fileName = `${
fork icon0
star icon2
watch icon3

+ 9 other calls in file

2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
* @example
*
* async.applyEach([enableSearch, updateSchema], 'bucket', callback);
*
* // partial application example:
* async.each(
*     buckets,
*     async.applyEach([enableSearch, updateSchema]),
*     callback
* );
fork icon0
star icon2
watch icon1

+ 5 other calls in file

98
99
100
101
102
103
104
105
106
107
    // Get array of rooms
    connectionObj.getRoomNames(asyncCallback);
},
function(roomNames, asyncCallback) {
    // leave all rooms
    async.each(roomNames,
        function(currentRoomName, asyncEachCallback) {
            pub.events.emit("roomLeave", connectionObj, currentRoomName, function(err) {asyncEachCallback(null);});
        },
        function(err) {
fork icon0
star icon2
watch icon1

+ 3 other calls in file

1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
    callback(err);
    return;
}

// Set all options in options object. If any fail, an error will be sent to the callback.
async.each(Object.keys(options), function(currentOptionName, asyncCallback) {
    appObj.setOption(currentOptionName, options[currentOptionName]);
    asyncCallback(null);
},
        function(err) {
fork icon0
star icon2
watch icon1

+ 5 other calls in file

853
854
855
856
857
858
859
860
861
if (folderIds.length > 0) {
    requestFolders = folderIds;
}

let allMessages = [];
return Async.each(requestFolders, (folderId, callback) => {

    const folderUri = `me/mailFolders/${folderId}/messages${uri}`;
    client.api(folderUri).get().then((resMessages) => {
fork icon2
star icon1
watch icon6

428
429
430
431
432
433
434
435
436
437
async.eachOfSeries(subpackagesEntriesMap, (deps, packageRoot, callback) => {
  mpx.currentPackageRoot = packageRoot
  mpx.componentsMap[packageRoot] = mpx.componentsMap[packageRoot] || {}
  mpx.staticResourcesMap[packageRoot] = mpx.staticResourcesMap[packageRoot] || {}
  mpx.subpackageModulesMap[packageRoot] = mpx.subpackageModulesMap[packageRoot] || {}
  async.each(deps, (dep, callback) => {
    dep.addEntry(compilation, (err, { resultPath }) => {
      if (err) return callback(err)
      dep.resultPath = mpx.replacePathMap[dep.key] = resultPath
      callback()
fork icon347
star icon0
watch icon92

+ 9 other calls in file

15
16
17
18
19
20
21
22
23
24
createMode: (request, response) => {

  let mode = new Mode();
  mode.name = request.payload.name;

  Async.each(request.payload.devices, (device, callback) => {
    Device.findById(device.id, (error, deviceObj) => {
      if (error) {
        callback(Boom.badImplementation('Could not fetch device for mode.'));
      }
fork icon0
star icon1
watch icon1

+ 21 other calls in file

1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
function loadAsset(player, entry, callback) {
    player.getAssetData(`assets/${entry.storagePath}/cubicModel.json`, "json", (err, data) => {
        data.textures = {};
        const mapsList = data.maps;
        data.textures = {};
        async.each(mapsList, (key, cb) => {
            const canvas = document.createElement("canvas");
            canvas.width = data.textureWidth;
            canvas.height = data.textureHeight;
            const ctx = canvas.getContext("2d");
fork icon0
star icon0
watch icon1

+ 21 other calls in file

1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
    exports.data.clientId = clientId;
    loadPlugins();
}
function loadPlugins() {
    SupClient.fetch(`/systems/${SupCore.system.id}/plugins.json`, "json", (err, pluginsInfo) => {
        async.each(pluginsInfo.list, (pluginName, cb) => {
            SupClient.loadScript(`/systems/${SupCore.system.id}/plugins/${pluginName}/bundles/typescriptAPI.js`, cb);
        }, (err) => {
            // Read API definitions
            let globalDefs = "";
fork icon0
star icon0
watch icon0

+ 20 other calls in file

1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
        }
        plugin.loadAsset(this, entry, (err, data) => { onAssetLoaded(err, entry, data); });
    });
}
_initPlugins(callback) {
    async.each(Object.keys(SupRuntime.plugins), (name, cb) => {
        const plugin = SupRuntime.plugins[name];
        if (plugin.init != null)
            plugin.init(this, cb);
        else
fork icon0
star icon0
watch icon0

+ 69 other calls in file