Skip to content

Instantly share code, notes, and snippets.

@possan
Created July 10, 2012 14:08
Show Gist options
  • Save possan/3083478 to your computer and use it in GitHub Desktop.
Save possan/3083478 to your computer and use it in GitHub Desktop.
Simple asynchronous mapper in javascript
Array.prototype.mapAsync = function(mapper, finalcallback) {
var waiting = 0;
var that = this;
var newlist = [];
this.forEach(function(item) {
// console.log('starting async mapper', item);
waiting ++;
setTimeout(function() {
mapper(item, function(newitem) {
newlist.push(newitem);
// console.log('async mapper done', item);
setTimeout(function() {
waiting --;
if (waiting === 0) {
// console.log('firing final callback');
finalcallback(newlist);
}
}, 1);
});
}, 1);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment