Last active
August 29, 2015 14:24
-
-
Save sabind/91d8e13ff378767e2640 to your computer and use it in GitHub Desktop.
_.each does not replace async
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
| 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(); | |
| } | |
| }); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This loop will NOT properly detect errors.