Skip to content

Instantly share code, notes, and snippets.

@agar3s
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agar3s/1a0feba4feb08058d670 to your computer and use it in GitHub Desktop.
Save agar3s/1a0feba4feb08058d670 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++;
this.next(params);
};
module.exports = SyncMapIterator;
var SyncMapIterator = require('./syncMapIterator');
var map = new SyncMapIterator([5,4,3,2,1,0], function(value, params, callback){
console.log('Waiting for ' + value + ' seconds..');
setTimeout(function(){
params.elements.push(value);
callback(params);
}, value*1000);
}, function(params){
console.log(params);
console.log('finished');
});
map.next({elements:[]});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment