Created
December 15, 2013 10:35
-
-
Save cuipengfei/7971376 to your computer and use it in GitHub Desktop.
functional js async loops
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
| function loadUsers(userIds, load, done) { | |
| var users = [] | |
| var count = 0 | |
| userIds.forEach(function (id) { | |
| load(id, function (user) { | |
| users[userIds.indexOf(user.id)] = user | |
| count++ | |
| //can not use users.length here | |
| if (count == userIds.length) { | |
| done(users) | |
| } | |
| }) | |
| }) | |
| } | |
| module.exports = loadUsers |
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
| function loadUsers(userIds, load, done) { | |
| var completed = 0 | |
| var users = [] | |
| userIds.forEach(function(id, index) { | |
| load(id, function(user) { | |
| users[index] = user | |
| if (++completed === userIds.length) return done(users) | |
| }) | |
| }) | |
| } | |
| module.exports = loadUsers |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
forEach gives us the index