Created
April 12, 2018 14:35
-
-
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)
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
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