首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >异步函数自动返回

异步函数自动返回
EN

Stack Overflow用户
提问于 2018-08-31 05:48:53
回答 1查看 230关注 0票数 1

我正在使用react redux在我的应用程序中创建一个动作创建器。关键是,当我使用async await语法时,它会自动返回一个promise (没有"return"关键字)。但是,当我使用像then()这样的老式promise时,我必须显式地输入”关键字-否则它将返回undefined。这一切为什么要发生?

app.js (createStore):

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
export default [
  {
    loadData,
    path: '/',
    component: Landing,
    exact: true,
  },
];

landing.js

代码语言:javascript
运行
复制
function loadData(store) {
  return store.dispatch(fetchUser());
}
export { loadData };

当我使用异步等待

action.js

代码语言:javascript
运行
复制
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时,然后使用

代码语言:javascript
运行
复制
// 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,
    });
  });
};

“返回”关键字

代码语言:javascript
运行
复制
// 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,
    });
  });
};
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52105817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档