Last active
April 5, 2016 16:34
-
-
Save co3moz/0fc4694c84da16db34c4 to your computer and use it in GitHub Desktop.
Async Array Iterator
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.iterate = function (cb, done, timeout) { | |
((timeout != undefined) || (typeof timeout == "object") || (timeout = 5000)); | |
var total = this.length; | |
var result = []; | |
if (total == 0) { | |
return done(null, result); | |
} | |
var sent = false; | |
this.forEach(function (e, i) { | |
setTimeout(function () { | |
cb(e, function (data) { | |
if (data instanceof Error) { | |
if (!sent) { | |
done(data, null); | |
sent = true; | |
} | |
} else { | |
result[i] = data; | |
if (--total == 0 && !sent) { | |
done(null, result); | |
sent = true; | |
} | |
} | |
}) | |
}); | |
}); | |
if (timeout != null) { | |
setTimeout(function () { | |
if (total != 0 && !sent) { | |
done(Error("timeout"), null); | |
sent = true; | |
} | |
}, timeout); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
error example