end_lesslove2012
end_lesslove2012

Reputation: 107

Async function auto return

I'm using react redux to create an action creator in my app. The point is that when I use async await syntax, it auto returns a promise (without the "return" keyword). However, when I use old-style promise like then(), i have to explicitly type the "return" keyword - otherwise it will return undefined. Why does this happen?

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

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

enter image description here

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

enter image description here

"return" keyword

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

Upvotes: 1

Views: 445

Answers (1)

Estus Flask
Estus Flask

Reputation: 222503

async function always returns a promise, that's its purpose. In case there's no return value, it returns a promise of undefined.

As the reference states,

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.

This async function

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

is syntactic sugar for this function:

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

Upvotes: 2

Related Questions