How to use async

Comprehensive async code examples:

How to use async.until:

134
135
136
137
138
139
140
141
142
143
var mkdir = function (dir, callback) {
  self.emit('mkdir', dir);
  sftp.mkdir(dir, attrs, callback);
};

async.until(function () {
  return exists;
}, function (done) {
  // detect if the directory exists
  sftp.stat(dir, function (err, attr) {

How to use async.noop:

19
20
21
22
23
24
25
26
27
28
function _detect(eachFn, arr, iterator, mainCallback) {
  eachFn(arr, function (x, index, callback) {
    iterator(x, function (v, result) {
      if (v) {
        mainCallback(result || x);
        mainCallback = async.noop;
      } else {
        callback();
      }
    });

How to use async.promises:

221
222
223
224
225
226
227
228
229
230
	rmLists.forEach(u => this.remove(u))
	newLists.forEach(u => this.syncLoadList(u))
}
async isListCached(url){
	let err, file = global.storage.raw.resolve(LIST_DATA_KEY_MASK.format(url))
	const stat = await fs.promises.stat(file).catch(e => err = e)
	return (stat && stat.size >= 1024)
}
async filterCachedUrls(urls){
	if(this.debug) console.log('filterCachedUrls', urls.join("\r\n"))

How to use async.forEachLimit:

215
216
217
218
219
220
221
const [relativePath, devsFileAlreadyExist] = file;
const devs = this.devicesManager.getDevices();
let devsToUse = utils.shuffleArray(devs.filter((dev) => !devsFileAlreadyExist.includes(dev)));
devsToUse = devsToUse.slice(0, this.replicationCount - devsFileAlreadyExist.length);

async.forEachLimit(
  devsToUse,

How to use async.reflectAll:

130
131
132
133
134
135
136
137
138
139
    .then((answers) => callback({ ...answers, ...prefilled }));
}

function checkAllDependencies(callback) {
  async.parallel(
    async.reflectAll([checkPrimaryDependencies, checkSecondaryDependencies]),
    (error, results) => {
      const errors = results.map((result) => result.error).filter(Boolean);
      // all errors will be the same
      callback(errors.length ? errors[0] : null);

How to use async.foldl:

1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
async.mapLimit = doParallelLimit(_asyncMap);

// reduce only has a series version, as doing reduce in parallel won't
// work in many situations.
async.inject
	= async.foldl
	= async.reduce
		= function (arr, memo, iterator, callback) {
				async.eachOfSeries(
					arr,

How to use async.concatSeries:

57
58
59
60
61
62
63
64
65
}

var compiledMax = [], compiledMin = [];
var i = 0;

async.concatSeries(files, function(file, next) {
  if (i++ > 0) {
    options.banner = '';
  }

How to use async.reject:

5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
* Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Invoked with (err, results).
* @example
*
* async.reject(['file1','file2','file3'], function(filePath, callback) {
*     fs.access(filePath, function(err) {
*         callback(null, !err)
*     });
* }, function(err, results) {

How to use async.race:

4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
* completed. This function gets an error or result from the first function that
* completed. Invoked with (err, result).
* @returns undefined
* @example
*
* async.race([
*     function(callback) {
*         setTimeout(function() {
*             callback(null, 'one');
*         }, 200);

How to use async.memoize:

4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
*
* var slow_fn = function(name, callback) {
*     // do something
*     callback(null, result);
* };
* var fn = async.memoize(slow_fn);
*
* // fn can now be used as if it were slow_fn
* fn('some name', function() {
*     // callback

How to use async.cargo:

3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
* attached as certain properties to listen for specific events during the
* lifecycle of the cargo and inner queue.
* @example
*
* // create a cargo object with payload 2
* var cargo = async.cargo(function(tasks, callback) {
*     for (var i=0; i<tasks.length; i++) {
*         console.log('hello ' + tasks[i].name);
*     }
*     callback();

How to use async.dir:

3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
 *         callback(null, {hello: name});
 *     }, 1000);
 * };
 *
 * // in the node repl
 * node> async.dir(hello, 'world');
 * {hello: 'world'}
 */
var dir = consoleFunc('dir');

How to use async.mapValues:

4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
* functions have finished, or an error occurs. `result` is a new object consisting
* of each key from `obj`, with each transformed value on the right-hand side.
* Invoked with (err, result).
* @example
*
* async.mapValues({
*     f1: 'file1',
*     f2: 'file2',
*     f3: 'file3'
* }, function (file, key, callback) {

How to use async.compose:

3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
*     setTimeout(function () {
*         callback(null, n * 3);
*     }, 10);
* }
*
* var add1mul3 = async.compose(mul3, add1);
* add1mul3(4, function (err, result) {
*     // result now equals 15
* });
*/

How to use async.log:

4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
 *         callback(null, 'hello ' + name);
 *     }, 1000);
 * };
 *
 * // in the node repl
 * node> async.log(hello, 'world');
 * 'hello world'
 */
var log = consoleFunc('log');

How to use async.timeout:

5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
*         // return processed data
*         return callback(null, data);
*     });
* }
*
* var wrapped = async.timeout(myFunction, 1000);
*
* // call `wrapped` as you would `myFunction`
* wrapped({ bar: 'bar' }, function(err, data) {
*     // if `myFunction` takes < 1000 ms to execute, `err`

How to use async.some:

5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
* iteratee returns `true`, or after all the iteratee functions have finished.
* Result will be either `true` or `false` depending on the values of the async
* tests. Invoked with (err, result).
* @example
*
* async.some(['file1','file2','file3'], function(filePath, callback) {
*     fs.access(filePath, function(err) {
*         callback(null, !err)
*     });
* }, function(err, result) {

How to use async.forEachOfLimit:

129
130
131
132
133
134
135
136
137
138
    console.log('正处理以下番号影片...\n'.green + fanhao.toString().yellow);
    next(null, links);
}

function getItems(links, next) {
    async.forEachOfLimit(
        links,
        parallel,
        getItemPage,
        function (err) {

How to use async.groupByLimit:

198
199
200
201
202
203
204
205
206
207
    })
  })
} 
async groupByLimit(coll, limit, iteratee) {    
  return new Promise(async (resolve, reject) => { 
    async.groupByLimit(coll, limit, iteratee, (err, res) => {
      if (err) { 
        reject(err)
      } else {
        resolve(res)

How to use async.times:

727
728
729
730
731
732
733
734
735
736
    };
    s3.putBucketVersioning(params, done);
});

it('put 5 new versions to the object', done => {
    async.times(5, (i, putDone) => s3.putObject({
        Bucket: bucket,
        Key: key,
        Body: `test-body-${i}`,
    }, putDone), done);

How to use async.forever:

82
83
84
85
86
87
88
89
90
91

async.series(
  [
    function(callback) {
      var i = 1;
      async.forever(
        function(next) {
          CP_get.movies(
            { from: process.env.CP_RT, ids: true },
            500,

How to use async.forEach:

1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
        });
    });
},

cb=>{
    async.forEach(datasets, async dataset=>{
        inc_download_count(dataset);
        await dataset.save();
    }, cb);
},

How to use async.tryEach:

5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
* @param {Function} [callback] - An optional callback which is called when one
* of the tasks has succeeded, or all have failed. It receives the `err` and
* `result` arguments of the last attempt at completing the `task`. Invoked with
* (err, results).
* @example
* async.tryEach([
*     function getDataFromFirstWebsite(callback) {
*         // Try getting the data from the first website
*         callback(err, data);
*     },

How to use async.groupBySeries:

209
210
211
212
213
214
215
216
217
218
    })
  })
}
async groupBySeries(coll, limit, iteratee) {    
  return new Promise(async (resolve, reject) => { 
    async.groupBySeries(coll, limit, iteratee, (err, res) => {
      if (err) { 
        reject(err)
      } else {
        resolve(res)

How to use async.parallelLimit:

140
141
142
143
144
145
146
147
148
149
_.each(this.catalog.items, _.bind(function(i) {
  queue.push(as.apply(this.fetchHeaders, i.id));
}, this));

// Start,
as.parallelLimit(as.reflectAll(queue), this.options.concurrency, function(error, results) {
  var errors = _.filter(results, 'error').length;
  var updated = results.length - errors;

  done(errors ? _.filter(results, 'error') : null, {

How to use async.everyLimit:

136
137
138
139
140
141
142
143
144
145
function getMongoHost(hostList, port,role, cb) {
  var hosts = hostList.split(',');

  var detectedHost = undefined;

  async.everyLimit(hosts, 1, function(host, callback) {

    _getMongoHost(host, port, role, function(err, master) {
      if (err) {
        // server with specified role not found. Try next host.

How to use async.forEachSeries:

30
31
32
33
34
35
36
37
38
39
    populate: { path: 'event_category', model: primary.model(constants.MODELS.categories, categoryModel), select: "category_name description event_type" },
    select: 'display_name event_type event_category timestamp status createdAt updatedAt capacity aboutplace personaldetail discounts is_live is_approved isFormSubmitted',
    lean: true
}).then((events) => {
    let allEvents = [];
    async.forEachSeries(events.docs, (event, next_event) => {
        let totalPrice = 0;
        (async () => {
            let noofreview = parseInt(await primary.model(constants.MODELS.eventreviews, eventreviewModel).countDocuments({ eventid: mongoose.Types.ObjectId(event._id) }));
            async.forEach(event.discounts, (discount, next_discount) => {

How to use async.detectLimit:

215
216
217
218
219
220
221
  name = contentURL.basename;
}

var nodesIdsByTitle=map[name];

Async.detectLimit(nodesIdsByTitle, 2, (nodeId, callback) => {
  parentNode.service.getNodeById(nodeId, (error, node) => {

How to use async.concatLimit:

30
31
32
33
34
35
36
37
38
39
const getAllUpcomingFacebookEvents = function (user, callback, pages) {
  console.log(`Getting events for ${user}`);
  Facebook.getAllUpcomingFacebookEvents(user, callback, pages);
};

async.concatLimit(sources['facebook'], 1, getAllUpcomingFacebookEvents, function (err, res) {
  if (err) handleError(err, 'fetching facebook events');
  console.log(`${res.length} events downloaded`);
  const facebookEventIds = [];
  const makeRequest = function (facebookEvent, callback) {