sg_asyncEach. Like each, but async!
https://gist.github.com/706936
JavaScript
/*
https://gist.github.com/706936
*/
if (typeof console == 'undefined')
console = {
log:function(message){$(document.body).grab(new Element('p',{html:message}))}
}
/*
---
name : sg_asyncEach
description : sg_asyncEach is like each, but async!
authors : Thomas Aylott
copyright : © 2010 Thomas Aylott
license : MIT
provides : [sg_asyncEach, Array.sg_asyncEach, Object.sg_asyncEach, Elements.sg_asyncEach]
...
*/
;(function(){
var call = Function.call
function sg_asyncEachItem
( fn
, value
, key
, object
, callback
, THIS
){
if (THIS == null) THIS = this
var result
setTimeout(function(){
try {
result =
call.call
( fn
, THIS
, value
, key
, object
)
callback(false, result, object)
}
catch (error){
callback(error, result, object)
}
},
0);
}
function Object_sg_asyncEach(object, fn, callback, THIS){
for (var property in object)
sg_asyncEachItem.call
( this
, fn
, object[property]
, property
, object
, callback
, THIS
)
return object
}
Object.sg_asyncEach = Object_sg_asyncEach
function Array_sg_asyncEach(array, fn, callback, THIS){
for (var i = 0, l=array.length; i < l; ++i)
sg_asyncEachItem.call
( this
, fn
, array[i]
, i
, array
, callback
, THIS
)
return array
}
Array.sg_asyncEach = Array_sg_asyncEach
Array.prototype.sg_asyncEach = function(fn, callback, THIS){
return Array_sg_asyncEach.call(this, this, fn, callback, THIS)
}
if (Elements && Elements.implement)
Elements.implement('sg_asyncEach', Array.prototype.sg_asyncEach)
}())
// // // // // // // // // // // // // // // // // // // // //
// works as a generic!
Array.sg_asyncEach([1, 2, 3],
...