Skip to content

Instantly share code, notes, and snippets.

@possan
Created July 11, 2012 14:13
Show Gist options
  • Save possan/3090607 to your computer and use it in GitHub Desktop.
Save possan/3090607 to your computer and use it in GitHub Desktop.
Asynchronous mapper in javascript with timeout
Array.prototype.mapAsync = function(mapper, finalcallback, timeout) {
var mappertimeout = timeout || 10000;
var waiting = 0;
var that = this;
var newlist = [];
var _donecallback = function() {
waiting --;
console.log('after async mapper done');
if (waiting === 0) {
console.log('firing final callback');
finalcallback(newlist);
}
};
this.forEach(function(item) {
console.log('starting async mapper', item, waiting);
waiting ++;
setTimeout(function() {
var imdone = false;
setTimeout(function() {
if (imdone) return;
console.log('mapper timed out!', item);
imdone = true;
_donecallback();
}, mappertimeout);
try {
mapper(item, function(newitem) {
if (imdone) return;
console.log('mapper done.', item, newitem);
imdone = true;
if (typeof newitem !== 'undefined') newlist.push(newitem);
_donecallback();
});
} catch(error) {
console.error('mapper crashed', item, error);
if (imdone) return;
imdone = true;
_donecallback();
}
}, 1);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment