Last active
December 10, 2015 19:48
-
-
Save nickleefly/4484327 to your computer and use it in GitHub Desktop.
insert 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 insertElement = function(data, callback) { | |
var timeout = Math.ceil(Math.random() * 1000); | |
setTimeout(function() { | |
callback(null, data); | |
}, timeout); | |
}; | |
var insertAll = function(coll, callback) { | |
var queue = coll.slice(0), | |
elem; | |
(function iterate() { | |
if (queue.length === 0) { | |
callback(); | |
return; | |
} | |
elem = queue.splice(0, 1)[0]; | |
insertElement(elem, function(err, elem) { | |
if (err) { throw err; } | |
console.log(elem + ' inserted'); | |
//setTimeout(iterate, 0) | |
process.nextTick(iterate); | |
}); | |
})(); | |
}; | |
insertAll([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function() { | |
console.log('insertAll fininshed'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment