0

My Store registers 2 actiontypes as follows:

Dispatcher.register(function (action) {
    switch (action.type) {
        case 'loadCar':
            loadCar();
            break;
        case 'loadTyres':
            loadTyres();
            break;
    }
})

how can I assure, that loadCaris executed before loadTyres? Is there a way to wait for this depending method without having to execute loadCar everytime I want to just loadTyres?

FranBran
  • 1,017
  • 2
  • 11
  • 32

1 Answers1

0

Below is an untested pattern you might try. You'll maybe need to start dispatching a start loadcar, loadcar completed for example to complete this (see here).

// pick your favorite Promise library
var Promise = require('bluebird'); 

Dispatcher.register(function (action) {
    switch (action.type) {
        case 'loadCar':
            // need to be async here
            loadCar(action.carId).then(function(car) {
                // this eventually returns                      
            });
            break;
        case 'loadTyres':
            // need to be async here
            loadTyres(action.carId).then(function(tyres) {

            })
            break;
    }
})

You could also save the Promise object and cache it so that it is the "current" car and then it wouldn't be reloaded (unless you remove it from the array).

var allCars = {};
function loadCar(id) {
    if(typeof allCars[id] === 'undefined') {
        allCars[id] = loadCarPromise(id);
    }
    return allCars[id];
}

You'll create a function that returns a Promise that will resolve with the specifics of the car data you're loading. You'll need to do whatever you would normally do there, but eventually call the resolve or reject callbacks to properly continue the Promise chain.

function loadCarPromise(id) {
    return new Promise(function(resolve, reject) {
        // do whatever you do to get
        // the car
        // when it's done, call resolve
        // or reject if there is a failure.
        // ex:
        $.ajax({
            url: 'api/car/' + id,
            success: function(data) {
                resolve(data);
            },
            error: function(err) {
                reject(err);
            }
        });
    });
}

And finally, loadTyres would use loadCar internally and only resolve itself when the tyre data has been returned.

function loadTyres(carId) {
    // the car is always loaded first, then the tyres
    // but if using the cache, the car will be
    // returned immediately (although you won't need
    // to worry about that)
    return loadCar(carId).then(function(car) {
        return new Promise(function(resolve, reject) {
            // do something to load the tyres
            // with the car info that was returned
            resolve(/* tyres data */);          
        });
    });
}
Community
  • 1
  • 1
WiredPrairie
  • 58,954
  • 17
  • 116
  • 143