Search code examples
javascriptreactjses6-promiseredux-thunkecmascript-2017

how to properly use the async and await keywords within a map


I have the following snippet of code

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

when i console log the posts, i get 2 functions returned. what is the proper way in which i should call the fetch comments for this function to return me the desired value?


Solution

  • Add this:

    const postsResult = await Promise.all(posts)