【问题标题】:Redux connect chaining async actionsRedux 连接链异步操作
【发布时间】:2016-05-30 06:52:32
【问题描述】:

我正在尝试设置 redux、react-redux 和 redux-thunk。想法通常进展顺利,但我有一个问题,当将多个异步操作链接在一起时,事情应该如何看待。

具体来说,我有一个场景,可以通过另一个可以调用它们的动作单独或间接调用这些动作。我的问题是selectItem 如果我想成为惯用语,应该如何编写?

action.js

export function fetchByContext(contextId) { 
    return dispatch => {
        _fetchByContext(messages => { 
            dispatch({ type: RECEIVE_MESSAGES, ... });
        });
    };
};

export function subscribeByContext(contextId) {
    return dispatch => {
        _subscribeByContext(messages => { 
            dispatch({ type: RECEIVE_MESSAGES, ... });
        });
    };
};

export function selectItem(contextId) {
    return dispatch => {
        subscribeByContext(contextId)(dispatch);
        fetchByContext(contextId)(dispatch);
    };
};

【问题讨论】:

  • async,await keywork 可能有帮助

标签: reactjs redux react-redux redux-thunk


【解决方案1】:

我认为关键在于 (ref):

内部函数的任何返回值都可以作为调度本身的返回值

如果fetchByContext()subscribeByContext() 的内部函数返回一个promise,它们可以串联或从selectItem() 并行运行。一个未经测试的实现,假设 _fetchByContext()_subscribeByContext() 都没有返回一个承诺:

export function fetchByContext(contextId) { 
    return dispatch => {
        return new Promise((resolve, reject) => {
            _fetchByContext(messages => { 
                dispatch({ type: RECEIVE_MESSAGES, ... });
                resolve(messages);
            });
        });
    };
};

export function subscribeByContext(contextId) {
    return dispatch => {
        return new Promise((resolve, reject) => {
            _subscribeByContext(messages => { 
                dispatch({ type: RECEIVE_MESSAGES, ... });
                resolve(messages);
            });
        });
    };
};

export function selectItem(contextId) {
    return dispatch => {
        // CALL IN SERIES
        return dispatch(subscribeByContext(contextId))
            .then(() => dispatch(fetchByContext(contextId)));
        // CALL IN PARALLEL (alternative to the code above; this is probably not what you want - just keeping for reference)
        return Promise.all(
            dispatch(subscribeByContext(contextId)),
            dispatch(fetchByContext(contextId))
        );
    };
}

再次请注意,上面的代码未经测试,只是希望提供一个通用解决方案的想法。

【讨论】:

    猜你喜欢
    • 2017-09-26
    • 2018-01-31
    • 1970-01-01
    • 2019-04-01
    • 2021-04-03
    • 2020-04-23
    • 2017-05-03
    • 2016-06-02
    • 1970-01-01
    相关资源
    最近更新 更多