以下是您可以尝试的未经测试的模式。例如,您可能需要开始发送 start loadcar、loadcar completed 来完成此操作(请参阅 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;
}
})
您还可以保存 Promise 对象并将其缓存,使其成为“当前”对象
car 然后它不会被重新加载(除非你从数组中删除它)。
var allCars = {};
function loadCar(id) {
if(typeof allCars[id] === 'undefined') {
allCars[id] = loadCarPromise(id);
}
return allCars[id];
}
您将创建一个返回 Promise 的函数,该 Promise 将使用您正在加载的 car 数据的细节进行解析。你需要做你通常在那里做的任何事情,但最终调用 resolve 或 reject 回调以正确地继续 Promise 链。
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);
}
});
});
}
最后,loadTyres 将在内部使用loadCar,并且仅在返回轮胎数据时自行解析。
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 */);
});
});
}