This is more a question about promises than about Ractive, so this MDN article would be worth a read, though it's a bit heavy.
Basically though, if you want to wait until several operations have finished, use Promise.all
:
var ready = Promise.all([
getJSON( '/data.json' ), // async (returns a promise)
domReady(), // async
reticulateSplines() // sync
]);
getJSON
and domReady
will be executed simultaneously. So will reticulateSplines
, not that it matters since it's synchronous. The value of ready
is now a promise that will fulfil with an array containing the results of those three operations:
ready.then( function ( values ) {
var data = values[0];
var document = values[1];
var splines = values[2];
// some code happens
}).catch( function ( err ) {
// if something went wrong with any of those three
// functions (e.g. couldn't find data.json), we'll
// end up here
});
If you're transpiling your code with something like babel, you can also use destructuring:
ready.then( ([ data, document, splines ]) => {
// some code happens
}).catch( err => {
// handle error
});
Another useful function if you're dealing with maybe-sync-maybe-async stuff (though it really is better to avoid that sort of thing) is Promise.resolve
:
function crazyTown () {
if ( Math.random() < 0.5 ) {
return 'sync!';
} else {
return new Promise( function ( fulfil, reject ) {
setTimeout( function () {
fulfil( 'async!' );
}, 500 );
});
}
}
Promise.resolve( crazyTown() ).then( function ( type ) {
console.log( type );
});
If your browser supports promises natively, Ractive will use those (i.e. Ractive.Promise === window.Promise
) - if not, it uses its own spec-compliant implementation.