异步功能自动返回

时间:2018-08-30 21:48:53

标签: reactjs redux react-router react-redux serverside-rendering

我正在使用 react redux 在我的应用中创建动作创建者。关键是,当我使用 async await 语法时,它会自动返回一个promise(没有“ return” 关键字)。但是,当我使用 then()之类的老式约定时,我必须明确键入“ return” 关键字-否则它将返回undefined。为什么会这样?

app.js (createStore):

app.get('*', (req, res) => {
  const store = createStore(reducers, applyMiddleware(reduxThunk));
  const promise = matchRoutes(RouteApp, req.path).map(({ route }) => {
    return route.loadData ? route.loadData(store) : null;
  });
  console.log(promise);
  Promise.all(promise).then(() => {
    res.send(renderApp(req, store));
  });
});

route.js:

export default [
  {
    loadData,
    path: '/',
    component: Landing,
    exact: true,
  },
];

landing.js

function loadData(store) {
  return store.dispatch(fetchUser());
}
export { loadData };

当我使用 异步等待 时:

action.js

export const fetchUser = () => async (dispatch) => {
  const res = await axios.get('https://react-ssr-api.herokuapp.com/users');
  dispatch({
    type: INFO_USER,
    payload: res.data,
  });
};

enter image description here

当我使用 promise然后 时:

// It doesn't work
export const fetchUser = () => (dispatch) => {
  axios.get('https://react-ssr-api.herokuapp.com/users').then((res) => {
    dispatch({
      type: INFO_USER,
      payload: res.data,
    });
  });
};

enter image description here

“返回” 关键字

// now it works
export const fetchUser = () => (dispatch) => {
  return axios.get('https://react-ssr-api.herokuapp.com/users').then((res) => {
    dispatch({
      type: INFO_USER,
      payload: res.data,
    });
  });
};

1 个答案:

答案 0 :(得分:2)

async函数总是返回一个承诺,这就是它的目的。如果没有返回值,它将返回undefined的承诺。

the reference所述,

  

返回值

     

一个Promise,它将使用异步返回的值来解决   函数,或因内部抛出未捕获的异常而被拒绝   异步功能。

async函数

export const fetchUser = () => async (dispatch) => {
  const res = await axios.get('https://react-ssr-api.herokuapp.com/users');
  dispatch({
    type: INFO_USER,
    payload: res.data,
  });
};

是此功能的语法糖:

export const fetchUser = () => (dispatch) => {
  return axios.get('https://react-ssr-api.herokuapp.com/users').then((res) => {
    dispatch({
      type: INFO_USER,
      payload: res.data,
    });
  });
};