redux-thunk 和 async/await 动作:如何将它们全部组合起来?

redux-thunk and async/await actions: how to combine them all?

下面的一段代码是我的操作之一,并且确实有效。

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-native 应用程序中使用 async/await,我想确保我没有做一些反模式或其他错误

您不需要 await

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

只需要在:

const responseJson = await response.json();

这是因为fetch语句returns一个Promise。所以 await 只需要 await 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");