Created
July 11, 2012 14:13
-
-
Save possan/3090607 to your computer and use it in GitHub Desktop.
Asynchronous mapper in javascript with timeout
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
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