Last active
December 15, 2015 19:09
-
-
Save rkatic/5309285 to your computer and use it in GitHub Desktop.
Some utility/example functions for sequential processing with Q.
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
function loop (fn, startValue) { | |
var deferred = Q.defer(), | |
finished = false; | |
function end (val) { | |
finished = true; | |
deferred.resolve(val); | |
} | |
function error (reason) { | |
finished = true; | |
deferred.reject(reason); | |
} | |
function next (val) { | |
try { | |
var ret = fn(end, val); | |
} catch (ex) { | |
error(ex); | |
} | |
if (!finished) { | |
Q(ret).then(next, error); | |
} | |
} | |
Q(startValue).then(next, error); | |
return deferred.promise; | |
} | |
function repeatNTimes (n, fn) { | |
return loop(function (end) { | |
if (n-- > 0) { | |
return fn(); | |
} else { | |
end(); | |
} | |
}); | |
} | |
function mapSequentially (array, fn, context) { | |
var index = -1, len = array.length; | |
var results = []; | |
return loop(function (end, val) { | |
if (~index) { | |
results[index] = val; | |
} | |
while (++index < len && !(index in array)); | |
if (index < len) { | |
return fn.call(context, array[index], index, array); | |
} else { | |
end(results); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment