Skip to content

Instantly share code, notes, and snippets.

@sabind
Last active August 29, 2015 14:24
Show Gist options
  • Select an option

  • Save sabind/91d8e13ff378767e2640 to your computer and use it in GitHub Desktop.

Select an option

Save sabind/91d8e13ff378767e2640 to your computer and use it in GitHub Desktop.
_.each does not replace async
var _ = require('lodash');
var numbers = [1, 2, 3, 4];
var length = numbers.length;
var hasError = false;
// We write a function that takes longer than the loop to complete.
var blowUp = function (current, callback) {
setTimeout(function() {
if (current === 2) { callback(current) }
}, 1000)
};
// Happy Case
var doSomething = function() {
console.log('I'm done');
}
// Unhappy Case
var doSomethingElse = function() {
console.log('There was an error');
}
_.each(numbers, function(number, index) {
// We will quickly complete this section without ever setting to true;
if (!hasError) {
blowUp(number, function(err, result) {
// This only happens after a full two seocnds have passed.
if (err) {
console.log(err);
hasError = true;
}
);
// The loop iteration finishes almost instantly
if (index === length) {
doSomething();
}
} else {
doSomethingElse();
}
});
@sabind
Copy link
Author

sabind commented Jul 11, 2015

This loop will NOT properly detect errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment