Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Last active December 25, 2015 07:29
Show Gist options
  • Select an option

  • Save jarrettmeyer/6939643 to your computer and use it in GitHub Desktop.

Select an option

Save jarrettmeyer/6939643 to your computer and use it in GitHub Desktop.
// An example of how to work with an array in a non-blocking
// loop.
// This will store our results.
var result = {
count: 0,
sum: 0,
toString: function () {
return "Count: " + result.count + ", Sum: " + result.sum;
}
};
// Let's actually declare our addtion function here.
function add(array, done) {
// We're using setImmediate to give control back to the Node process.
// We will run once, then queue up the next callback.
function addValue (value, callback) {
return setImmediate(function () {
result.count += 1;
result.sum += value;
callback();
});
};
// I don't think there's anything here that could throw an error,
// but we don't actually want to throw the error regardless.
// Instead, lets catch it and include it in the callback.
try {
if (array.length > 0) {
addValue(array.shift(), function () {
add(array, done);
});
} else {
// There are no more items in the array, so fire the callback.
done(null, result);
}
} catch (e) {
done(e, result);
}
};
// Declare our array and run our code.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
add(array, function(err, res) {
if (err) {
console.error("Error: " + err);
return;
}
console.log("Result: " + res);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment