Created
October 22, 2013 03:47
-
-
Save andrewwakeling/7094918 to your computer and use it in GitHub Desktop.
A simple example showing how to use async to parallelize several invocations to asynchronous functions and wait for the result.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A simple example showing how to use async to parallelize several invocations to asynchronous functions and wait for the result. | |
var async = require('async'); | |
/** | |
* A very simple asynchronous function which takes in a number and invokes the callback with that number incremented by 1. | |
* @param number | |
* @param cb(err, result) | |
*/ | |
function addOne(number, cb) { | |
process.nextTick(function() { | |
cb(null, number + 1); | |
}); | |
} | |
/** | |
* Takes in an array of numbers. Creates a number of callbacks and invokes async.parallel. | |
* @param numbers | |
* @param cb(err, result) | |
*/ | |
function addOneToNumbers(numbers, cb) { | |
var callbacks = []; | |
numbers.forEach(function(number) { | |
callbacks.push(async.apply(addOne, number)); | |
}); | |
async.parallel(callbacks, cb); | |
} | |
addOneToNumbers([1,2,3,4,5,6,7,8,9, 10], function(err, result) { | |
console.log(err); | |
console.log(result); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment