[url=http:/civis/viewtopic.php?p=26027177#p26027177:2t693as4 said:
svdsinner[/url]":2t693as4]Any suggestions on how I can make it not-ugly to get multiple async answers and then launch a single function with results combined from the async callbacks and the original calling scope?
There have been a bunch of correct answers but I feel like answering this question for js practice.
The Node community bounced back and forth in the 0.1-0.3 era about promises and wound up adopting the convention of callback in last position and the callback having an error as its first parameter. This resulted in a lot of chaining libraries with slightly different APIs that all basically work the same. Looks like shade1978 posted the async version. I've always preferred chaining style versions of that api or step version:
Code:
function doWork(arg1, arg2) {
Step(
//the function names here are only for debugging
function setup() {
AsyncApi.DoSomethingToCompute1(someArgs, this.parallel());
AsyncApi.DoSomethingToCompute2(someArgs, this.parallel());
},
function complete(err, arg3, arg4) {
SomehowCallThisFunction(arg1, arg2, arg3, arg4);
}
)
}
for (var i=0, ii = 20; i < ii; i++) {
doWork(someArray[i], someOtherArray[i].data)
}
Since then, a LOT more effort as gone into the promises stuff and promises (Promises/A+ as opposed to Promises/A or Promises/B) are now being baked into the ES6 standard and asynchronous DOM APIs going forward. As such, it's good to at least have some understanding of how they work. Promises offer better chaining composition but there's an object allocation overhead with each promise since there's a deferred being constructed in the background and that's the primary reason the node guys pulled promises out of the node core. The most complete promise library is Q and my preferred small standalone implementation is RSVP. I'll also mention that when ES6 is more widely available you can get generator versions of this stuff using task.js or something similar. Here's the problem in Q on node:
Code:
function doWork(arg1, arg2) {
return Q.all([
Q.nfcall(AsyncApi.DoSomethingToCompute1, someArgs),
Q.nfcall(AsyncApi.DoSomethingToCompute2, someArgs)
]).spread(function(arg3, arg4) {
// bonus extra returns allow the chain to continue
return SomehowCallThisFunction(arg1, arg2, arg3, arg4);
});
}
for (var i=0, ii = 2; i < ii; i++) {
doWork(someArray[i], someOtherArray[i].data)
// the chain can be continued, e.g.: doWork(1, 2).then(console.log)
}
And then you get to the more exotic solutions. They're generally overkill for a problem this small but if you're doing a significant amount of async chaining they're potentially worth looking into.
One I haven't really seen explored in js is declarative dataflow. You build a graph of data dependencies, run them through a function that figures things out and wires the deps together, and then execute it. The implementation I'm most familiar with is Prismatic's graph (source) which is in Clojure. When they made that blog post I put together a hacky toy implementation because I was explaining it to someone at the time. The implementation is not async but it'd be fairly easy to turn it into a chain of promises without changing the api. Here's what the example problem would look like:
Code:
var doWork = eagerCompile({
arg3: function() { return AsyncApi.DoSomethingToCompute1(someArgs); },
arg4: function() { return AsyncApi.DoSomethingToCompute2(someArgs); },
out: function(arg1, arg2, arg3, arg4) {
return SomehowCallThisFunction(arg1, arg2, arg3, arg4);
}
});
for (var i=0, ii = 20; i < ii; i++) {
doWork({arg1: someArray[i], arg2: someOtherArray[i].data});
}
Something that IS more developed is the functional reactive programming model. I first heard of it via Microsoft Research and their Rx extensions stuff and I believe the Netflix guys use it as their core asynchronous eventing abstraction (they have a series of posts about it on their tech blog). The best javascript implementation is bacon.js. Other implementations are notably slower and Microsoft's follows .Net naming conventions instead of js naming conventions, which annoys me greatly. FRP can introduce a fairly significant amount of overhead and is kind of hard to wrap your head around (IMO, types help with this) so I've never introduced it to a team and have only messed around with it on my own projects. The code below is converting each input into a stream of values and then merging the streams at the end. If SomehowCallThisFunction returns a value, you can continue streaming the output values.
Code:
var arg1 = Bacon.fromArray(someArray);
var arg2 = Bacon.fromArray(someOtherArray).map('data');
var arg3 = arg1.flatMap(function(_){ return Bacon.fromNodeCallback(AsyncApi.DoSomethingToCompute1, someArgs); })
var arg4 = arg1.flatMap(function(_){ return Bacon.fromNodeCallback(AsyncApi.DoSomethingToCompute2, someArgs); })
Bacon.combineWith(SomehowCallThisFunction, arg1, arg2, arg3, arg4);
The last technique I'm reasonably familiar with is Communicating Sequential Processes (i.e. goroutines) which you can currently only implement in javascript via source code transformation so you're looking at a compile to js language or at least a transpiler or . The rough idea is that you transform linear code into a state machine where the nodes are the callback handlers and the edges are success/error conditions. I've never had to implement it so that might be wrong. In any case, the implementation I've worked with is Clojurescript's core.async :
Code:
(ns playground.core
(:require [cljs.core.async :as async :refer [<! >!]])
(:require-macros [cljs.core.async.macros :as m :refer [go]]))
(doseq [i (range 20)
arg1 (get someArray i)
arg2 (:data (get someOtherArray i))]
(go (let [arg3 (async/chan)
arg4 (async/chan)]
(.DoSomethingToCompute1 AsyncApi someArgs #(async/put! arg3 %))
(.DoSomethingToCompute2 AsyncApi someArgs #(async/put! arg4 %))
(somehow-call-this-function arg1 arg2 (<! arg3) (<! arg4)))))
It's not particularly attractive and doesn't really do the idea justice and I'm running out of steam on this post so I don't want to write the macro/helper functions to do it nicely. I really like this model. It's fairly easy to reason about and everything composes like I expect.
Finally, Mozilla has a macro system for javascript and at least one guy is poking around at syntax for monads in js. He actually has a whole set of Haskell ported ideas in code but I'm not familiar enough with the concepts to make use of them.
I think that covers everything. If anybody has an async model I missed, I'd be interested in hearing about it.