Last active
December 20, 2015 09:59
-
-
Save darsain/6111985 to your computer and use it in GitHub Desktop.
Handling of multiple parallel async resolutions in one main callback.
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
/** | |
* Handling of multiple parallel async resolutions in one main callback. | |
* | |
* @param {Function} callback Function executed after all async stuff has finished. | |
* | |
* @return {Function} Proxy generator. | |
*/ | |
function parallela(callback) { | |
var args = {}; | |
var proxies = 0; | |
/** | |
* Generate and register a proxy that has to be executed | |
* for final callback to be fired. | |
* | |
* @param {String} name Name of the object key for storing arguments. | |
* @param {Integer} argNo Index of argument to save. Omit to save all. | |
* | |
* @return {Function} Proxy. | |
*/ | |
return function (name, argNo) { | |
if (typeof name !== 'string') { | |
name = false; | |
} | |
proxies++; | |
/** | |
* Proxy function that saves needed argument, | |
* and executes final callback when last in queue. | |
* | |
* @return {Void} | |
*/ | |
return function () { | |
if (name) { | |
args[name] = argNo == null ? arguments : arguments[argNo]; | |
} | |
if(!--proxies) { | |
callback(args); | |
} | |
}; | |
}; | |
} |
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
/** | |
* Simulating async cb execution. | |
* | |
* @param {Mixed} ret Value to be returned asynchronously. | |
* @param {Function} cb Callback that will receive the value. | |
* | |
* @return {Void} | |
*/ | |
function hey(ret, cb) { | |
setTimeout(function () { | |
cb(null, ret); | |
}, Math.random()*90+10); | |
} | |
// Create a new paralella and save the proxy generator. | |
var proxy = parallela(function (result) { | |
console.log(result); | |
}); | |
// Simulate async execution of callbacks from proxy generator. | |
hey('this is foo', proxy('foo', 1)); | |
hey('this is bar', proxy('bar')); // note: unspecified argNo | |
hey('this is baz', proxy('baz', 1)); | |
// If you don't want to save any arguments, just create an empty proxy. | |
hey('none will see this', proxy()); | |
/* | |
When all hey()s have finished, console.log from main callback will report this arguments map: | |
{ | |
foo: 'this is foo', | |
bar: [ | |
null, | |
'this is bar' | |
], | |
baz: 'this is baz' | |
} | |
You can omit `argNo` argument in proxy generator and save the whole | |
`arguments` array if you need multiple arguments, or error handling. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment