Last active
December 21, 2015 09:19
-
-
Save SimonRichardson/6284212 to your computer and use it in GitHub Desktop.
Listener/Observable based lazy async. It holds onto a function until it has been fulfilled, then it holds onto the captured response so that any future subscribers are also notified (in a lazy way). This is stateful in many ways and can be used for a generator in Streams and Promises in squishy-pants or similar libraries.
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 lazyAsync(f) { | |
| var args = [].slice.call(arguments).slice(1), | |
| listeners = [], | |
| captured; | |
| f.apply(null, [ | |
| function() { | |
| captured = [].slice.call(arguments); | |
| for(var i = 0, total = listeners.length; i < total; i++) { | |
| listeners[i].apply(null, captured); | |
| } | |
| listeners.length = 0; | |
| }, | |
| function() { | |
| listeners.length = 0; | |
| }, | |
| args | |
| ]); | |
| return function(f) { | |
| if (captured) f.apply(null, captured); | |
| else listeners.push(f); | |
| }; | |
| } | |
| var async = lazyAsync( | |
| function(resolve, reject, args) { | |
| setTimeout(function() { | |
| resolve(args[0]); | |
| }, 100); | |
| }, | |
| 1 | |
| ); | |
| async( | |
| function() { | |
| console.log('Finish 1', arguments); | |
| } | |
| ); | |
| async( | |
| function() { | |
| console.log('Finish 2', arguments); | |
| } | |
| ); | |
| setTimeout( | |
| function() { | |
| async( | |
| function() { | |
| console.log('Finish 3', arguments); | |
| } | |
| ); | |
| }, | |
| 500 | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment