Skip to content

Instantly share code, notes, and snippets.

@getify
Last active August 29, 2015 14:25
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 getify/d152aa94a6e6dfad717a to your computer and use it in GitHub Desktop.
Save getify/d152aa94a6e6dfad717a to your computer and use it in GitHub Desktop.
what is this technique called? async (double) latch? here's 3 different variations to consider...
var WHAT_IS_THIS_PATTERN = (function(){
var buffer;
SOMETHING_ASYNC(function(v){
if (buffer === undefined) buffer = v;
else buffer(v);
});
return function(cb) {
if (buffer === undefined) buffer = cb;
else cb(buffer);
};
})();
// later:
WHAT_IS_THIS_PATTERN(function(val){
// ..
});
var buffer;
function handle(v) {
buffer = v;
}
SOMETHING_ASYNC(function(v){
handle(v);
});
SOMETHING_ELSE_ASYNC(function(cb){
if (buffer === undefined) handle = cb;
else cb(buffer);
});
var buffer, fn;
SOMETHING_ASYNC(arg,function(val){
if (fn) fn(val);
else buffer = val;
});
SOMETHING_ELSE_ASYNC(function(cb){
if (buffer === undefined) fn = cb;
else cb(buffer);
});
@DrBoolean
Copy link

Some interesting patterns for sure. I think I've done very similar things with a place holder variable too, but I can't seem to find a name.

I can say that a functional approach could be to use the concept of applicative functors to achieve the result.

var future_value_1 = Future.of(x);
var future_value_2 = Future.of(y);
var two_arg_fn = curry(function(x,y){ /* both are available */ })

liftA2(two_arg_n, future_value_1, future_value_2)
// Future.of(result_of_two_arg_fn)

Where the two_arg_fn will be run when both are complete.

This will do something simliar under the hood so i guess that would still need a name of it's own :)

I'll ask around

@DrBoolean
Copy link

I should mention there's also "OR" captured by a monoid:

Future.of(x).concat(Future.of(y))
// Future.of(WHICHEVER_FINISHES_FIRST)

There are names to the concepts of combining two things in one way or another (monoids) and applying a function to several values in contexts (applicative functors).

The concepts aren't specific to async values (we can combine anything with the same interface, etc). For the async vals the interfaces are implemented with the nameless patterns above...so I guess we still need a name.

@DrBoolean
Copy link

Oh, one last thing. The "finish first" monoid isn't the normal, intuitive application. Just a specialized version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment