Search code examples
javascriptjqueryajaxbackbone.jsasynchronous

Managing lots of backbone async requests


I am building a single page web application. When a user for example opens a case in the application, I need to load various data asynchronously.

However, I only want to present the case to the user when all that data has finished loading.

I currently use Backbone to fetch collections of data asynchronously.

Is there any standard or usual way of possibly registering various fetches and getting an event when they have all completed?

I'm considering building an elaborate system of bools to do this but I am wondering if maybe there is not some plugin that already does this.

The basic idea is: Register a bunch of backbone fetches and associate them with somthing like load:case:data

When all of those fetches complete, I get an event like load:case:data completed. At that point I can listen to that event and display the case.


Solution

  • I would recommend looking at the Q promise Library (Q.all) or BlueBird (Promise.all) and then you can just sync the promises returned from the fetch methods.

    You can also use plain jQuery when to do that. e.g.:

    $.when(someCollection.fetch(), anotherCollection.fetch()).done(function(){
       // All Completed, do next thing
    });
    

    One thing you can also use as an alternative to Q, BlueBird and jQuery is native Promise.all ES6 approach, look at the following table for support, and see if it matches your target browsers.

    https://kangax.github.io/compat-table/es6/