-
-
Save getify/11147684 to your computer and use it in GitHub Desktop.
// using asynquence+iterable sequences | |
var domready; | |
ASQ() | |
// wait for `domready` before we proceed | |
.seq( domready = ASQ.iterable() ) | |
.gate( | |
requestJSON( "foo.json" ), | |
requestJSON( "bar.json" ) | |
) | |
.val( transformJSONs ) | |
.seq( uploadJSON ) | |
.seq( displayRecords ) | |
.or( handleError ); | |
$(document).ready( domready.next ); |
// using native promises | |
var domready; | |
Promise.all([ | |
new Promise(function(resolve){ | |
domready = resolve; | |
}), | |
requestJSON( "foo.json" ), | |
requestJSON( "bar.json" ) | |
]) | |
.then( transformJSONs ) | |
.then( uploadJSON ) | |
.then( displayRecords ) | |
.catch( handleError ); | |
$(document).ready( domready ); |
I did a fiddle of this with promises -- http://jsfiddle.net/modernserf/TyuPA/2/ -- and you only need a single .catch at the bottom if any of those methods throws an error. Also, the document ready Promise can be written as
var domReady = new Promise($);
$(fn)
is shorthand for $(document).ready(fn)
, and new Promise passes the resolve
callback as its first argument, so this is the same as
var domReady = new Promise(function (resolve, reject){
$(document).ready(resolve);
});
I know your second snippet is "more preferable" stylistically, but I am pushing back on the (IMO) anti-pattern that some are advocating of this "promise trigger extraction" (my terminology) approach so that you can ensure "separation of concerns" (their terminology) -- that is, creating the promise in a different location from where you take it's trigger and use it.
It's actually quite common that you DO need to keep the "separation of concerns", and my point is that my "iterable sequence" approach is vastly superior to this "promise trigger extraction" approach.
So your first snippet is more true to the nature of what I'm exploring, but your second snippet skips the spirit of what's at issue by losing the "separation of concerns".
@modernserf your domReady
approach is missing the same spirit that I just explained above ^^^^^^^ to @juandopazo, which is the point was to explore keeping the "separation of concerns" where the promise is created in a different location than where the dom-ready event binding occurs.
Also, I was trying to avoid the uglier function(){ return somePromise; })
approach you've introduced. My single usage of Promise.all(..)
seems a lot cleaner than what you're suggesting.
@getify I misunderstood your original code. I was expecting the requestJSON
calls to happen after domready
. Comment fixed.
@juandopazo now your first snippet looks identical to mine, eh? :)
@getify you're missing a couple of square brackets. Promise.all
takes an array.
Also, the good thing is that it highlights a probable bug: domready
isn't JSON data, but transformJSONs
will get an array with [undefined, data, data]
.
@juandopazo thanks for the catch on [ ]
. and on the possible "bug". :)
Fixed...
But more likely: