异步函数自动 return

Async function auto return

我正在使用 react redux 在我的应用程序中创建一个动作创建器。关键是当我使用 async await 语法时,它自动 returns 一个承诺(没有 "return" 关键字) .但是,当我使用像 then() 这样的旧式承诺时,我必须明确键入 "return" 关键字 - 否则它会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 };

当我使用 async await:

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,
  });
};

当我使用promise then:

// 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,
    });
  });
};

"return"关键字

// 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,
    });
  });
};

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

the reference所述,

Return value

A Promise which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.

这个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,
    });
  });
};