Skip to content

Instantly share code, notes, and snippets.

@cuipengfei
Created December 15, 2013 10:35
Show Gist options
  • Select an option

  • Save cuipengfei/7971376 to your computer and use it in GitHub Desktop.

Select an option

Save cuipengfei/7971376 to your computer and use it in GitHub Desktop.
functional js async loops
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
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
@cuipengfei

Copy link
Copy Markdown
Author

forEach gives us the index

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