如何解决Store中的操作之间的依赖关系

时间:2015-02-20 10:49:23

标签: javascript reactjs reactjs-flux

我的商店注册了2个动作类型如下:

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

我怎么能保证loadCarloadTyres之前执行?有没有办法等待这种依赖方法,而不必每次只想loadCar执行loadTyres

1 个答案:

答案 0 :(得分:0)

以下是您可能尝试的未经测试的模式。您可能需要开始调度start loadcarloadcar 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对象并对其进行缓存,使其成为" current" 汽车,然后它将不会被重新加载(除非你从阵列中删除它。)

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

您将创建一个返回Promise的函数,该函数将使用您正在加载的car数据的细节进行解析。您需要做通常在那里做的任何事情,但最终会调用resolvereject回调来正确继续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 */);          
        });
    });
}