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 */);
});
});
}