Here is a simple method/function from a project I work on.
loadCollection
is an asynchronous method which loads data from the server. Various methods may call it (some directly, others by triggering an event). The method itself does nothing other than load the data requested (this is specified by the provided collectionID).
The method may not actually need to load the data - if it finds it already loaded and it hasn’t been told to force_reload
, it returns the data it has, saving a round trip to the server.
The data requested is JSON format, but not exactly the format we want (there are some links/relationships we’d like to establish and this collection may need to replace one already in memory). So, when the data is returned, the callback to the ajax request executes an update function, which does that data updating/replacement as needed.
At that point, the data is ready to use and function calls any callback provided, passing in the newly returned data. Additionally, it resolves the Promise
which was created and returned, also passing in the data.
This way, the function can be called directly using the .then()
syntax to process the results of the call after it is complete, or - when called via say an event triggering - the event can pass in a callback, which is executed.
Multiple collections can be loaded at once and all of this data is all maintained in a list (an Array) which is modified via methods like COLLECTIONS.update.collectionReference()
and accessed via methods like the COLLECTIONS.get.collectionReference()
Written this way, the load function doesn’t care why you are loading data, it simply loads the data you requested and then executes any callback/resolves a promise. All of the handling of the data returned is done external to the load call and passed back out.
I’m not suggesting this method is perfect (I found a bug while I was writing this up!) But it’s a common pattern for me when handling data loaded from the server.
Anyway, hope this helps out a bit!
function loadCollection( collectionID, include_imagestores, force_reload, callback ) => {
return new Promise( ( resolve ) => {
const collection = COLLECTIONS.get.collectionReference( collectionID );
if ( collection && ( include_imagestores && collection.imageStores && collection.imageStores.length ) && !force_reload )
{
completeLoad( collection, resolve, callback );
return;
}
COLLECTIONS.load.dataFromServer( 'collection',
{
'collectionID' : collectionID,
'includeImageStores' : ( include_imagestores ) ? 1 : 0,
'forceReload' : ( force_reload ) ? 1 : 0
})
.then( ( data ) => {
COLLECTIONS.update.collectionList( data );
completeLoad( COLLECTIONS.get.collectionReference( collectionID ), resolve, callback );
});
});
function completeLoad( collection, resolve, callback ){
( typeof callback === 'function' ) &&
callback( collection );
resolve( collection );
}
}