Skip to content

Instantly share code, notes, and snippets.

@BlueMagnificent
Created April 12, 2018 14:35
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 BlueMagnificent/92c26fd9cd3602886c3798715c723c39 to your computer and use it in GitHub Desktop.
Save BlueMagnificent/92c26fd9cd3602886c3798715c723c39 to your computer and use it in GitHub Desktop.
Function to synchronize an asynchronous sets of operations (gotten from Node.js Design Patterns)
function isGenerator(obj) {
return 'function' == typeof obj.next && 'function' == typeof obj.throw;
}
function isGeneratorFunction(obj) {
var constructor = obj.constructor;
if (!constructor) return false;
if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true;
return isGenerator(constructor.prototype);
}
module.exports = function asyncFlow(generatorFunction) {
if(!isGeneratorFunction(generatorFunction))
{
throw new Error('paramter not a generator function');
}
var generator = generatorFunction(callback);
generator.next();
function callback(err) {
if (err) {
return generator.throw (err);
}
var results = [].slice.call(arguments, 1);
generator.next(results.length > 1 ? results : results[0]);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment