Last active
August 29, 2015 14:26
-
-
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.
This file contains 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
/** | |
* 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; |
This file contains 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
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