Last active
August 29, 2015 14:00
-
-
Save getify/11147684 to your computer and use it in GitHub Desktop.
Firing off a one-time async sequence after an event like DOMReady
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
// 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 ); |
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
// 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 ); |
@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". :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@juandopazo
Also, I was trying to avoid the uglier
function(){ return somePromise; })
approach you've introduced. My single usage ofPromise.all(..)
seems a lot cleaner than what you're suggesting.