Last active
December 22, 2015 03:39
-
-
Save maciejhirsz/6411605 to your computer and use it in GitHub Desktop.
Iteratively call an async method, get all callback results into a single array with preserved order and getting a single callback in return.
This file contains hidden or 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
# get a single result | |
@processOne requiredStringArgument, requiredNumberArgument, id, (result) -> | |
# single result of processOne method | |
console.log result | |
@processOne.interative @, requiredStringArgument, requiredNumberArgument, arrayWithIds, (results) -> | |
# multiple results of processOne method in an array, with order of arrayWithIds preserved | |
console.log results |
This file contains hidden or 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::iterative = (context, magicArgs..., callback) -> | |
# Yes, magic is involved | |
method = @ | |
count = null | |
# Figure out how many calls we have to make | |
for arg in magicArgs | |
if Array.isArray(arg) | |
count = arg.length | |
break | |
throw "No array passed as argument" if count is null | |
# Empty array? | |
return callback([]) if count is 0 | |
results = new Array(count) | |
for index in [0...count] | |
do (index) -> process.nextTick -> | |
args = [] | |
# | |
# Build the arguments for the method pass | |
# | |
for arg in magicArgs | |
if Array.isArray(arg) | |
args.push(arg[index]) | |
else | |
args.push(arg) | |
# | |
# Attach a callback to arguments | |
# | |
args.push (result) -> | |
results[index] = result | |
count -= 1 | |
callback(results) if count is 0 | |
# | |
# Trigger the method with the arguments | |
# | |
method.apply(context, args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment