如何在地图中正确使用async和await关键字

时间:2017-10-27 09:41:16

标签: javascript reactjs es6-promise redux-thunk ecmascript-2017

我有以下代码片段

export const fetchPosts = () => async dispatch => {
  const res = await axios.get(`${url}/posts`, { headers: { ...headers } });
  console.log(res.data);
  let posts = res.data.map(p => (p.comments = fetchComments(p.id)));
  console.log(posts);
  dispatch({ type: FETCH_POSTS, payload: res.data });
};

export const fetchComments = id => async dispatch => {
  console.log(id)
  const res = await axios.get(`${url}/posts/${id}/comments'`, {
    headers: { ...headers }
  });
  console.log("id", id);
  return res.data;
};

当我控制台登录帖子时,我得到2个函数返回。我应该用什么方法调用此函数的获取注释以返回所需的值?

1 个答案:

答案 0 :(得分:3)

添加:

const postsResult = await Promise.all(posts)