Skip to content

Instantly share code, notes, and snippets.

@agar3s
Created July 29, 2015 21:03
Show Gist options
  • Save agar3s/796d462741437748df0c to your computer and use it in GitHub Desktop.
Save agar3s/796d462741437748df0c to your computer and use it in GitHub Desktop.
This is a snippet for a pattern I used to use when I iterate over an Array of objects applying a map async function but the process needs to be sync.
/**
* Creates a new Sync MapIterator over objects with an asyncrhonus mapFunction
* @param {[array]} objects [object array to iterate over]
* @param {[Function]} mapFunction [function to apply over each object sync mode]
* @param {Function} done [function to call when it's done]
*/
var SyncMapIterator = function(objects, mapFunction, done){
this.objects = objects;
this.i = 0;
this.retries = 0;
this.mapFunction = mapFunction;
this.done = done;
};
SyncMapIterator.prototype.next = function(params) {
var self = this;
params = params || {};
if(this.i>=this.objects.length){
return this.done(params);
}
this.mapFunction(this.objects[this.i], params, function(newParams){
self.i++;
self.next(newParams);
});
};
SyncMapIterator.prototype.hasNext = function(){
return this.i < this.objects.length;
};
SyncMapIterator.prototype.retry = function(params) {
this.i--;
this.retries++;
next(params);
};
module.exports = SyncMapIterator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment