代码之家  ›  专栏  ›  技术社区  ›  realtebo

redux thunk和异步/等待操作:如何将它们结合起来?

  •  1
  • realtebo  · 技术社区  · 8 年前

    下面的代码是我的一个动作,实际上很有效。

    export const loadChannelList = () => { 
        return async (dispatch) => {
    
            dispatch ({
                type: CHANNEL_LIST_LOADING
            });
    
            try {
                const response  = await fetch('<my server url>');
                const responseJson = await response.json();
    
                dispatch ({
                    type: CHANNEL_LIST_LOADING_OK,
                    payload: "ok" // response.json()
                });
    
            } catch(error) {
                dispatch ({
                    type: CHANNEL_LIST_LOADING_FAILED,
                    payload: error
                });
            }
        };
    }
    

    在组件中,我这样使用它:

    componentWillReceiveProps(nextProps) {
            if (this.props.connectionStatus != 'ok' 
                && nextProps.connectionStatus == 'ok'
               ) {
                this.props.loadChannelList();
            }
    }
    

    我问你: 在使用redux thunk时,这是使用async/await的正确方法吗?

    我这样问是因为这是我第一次在redux thunk操作中在react本机应用程序中使用async/await,我想确保我没有出现反模式或其他错误

    1 回复  |  直到 8 年前
        1
  •  4
  •   Brett DeWoody    8 年前

    你不应该需要 await 日期:

    const response  = await fetch('<my server url>');
    

    仅在以下情况下需要:

    const responseJson = await response.json();
    

    这是因为 fetch Promise . 所以 等候 只需要 等候 结果 许诺 .

    下面是一个使用一些模拟函数的简化示例:

    // A fake asynchronous request
    function fetch(x) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve({
            data: x
          });
        }, 3000);
      });
    }
    
    // A fake Dispatch function
    function fakeDispatch(theData) {
      console.log(theData);
    }
    
    // A function to run on componentDidMount or similar
    async function getData(x) {
      const response = fetch(x);
      
      // call the Dispatch
      fakeDispatch(await response);
    }
    
    // componentDidMount
    console.log('Mounting component...');
    getData("some data");