How to use async correctly and wait for keywords within the map

I have the following code snippet

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 log messages to the console, I get 2 returned functions. What is the correct way I have to call comments for this function in order to return me the desired value?

+4
source share
1 answer

Add this:

const postsResult = await Promise.all(posts)
+3
source

Source: https://habr.com/ru/post/1688276/


All Articles