Skip to content

Instantly share code, notes, and snippets.

@rkatic
Last active December 15, 2015 19:09
Show Gist options
  • Save rkatic/5309285 to your computer and use it in GitHub Desktop.
Save rkatic/5309285 to your computer and use it in GitHub Desktop.
Some utility/example functions for sequential processing with Q.
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