如何在地图中正确使用 async 和 await 关键字
how to properly use the async and await keywords within a map
我有以下代码片段
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 个函数 returned。我应该如何调用此函数的提取注释以 return 我想要的值的正确方法是什么?
添加这个:
const postsResult = await Promise.all(posts)
我有以下代码片段
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 个函数 returned。我应该如何调用此函数的提取注释以 return 我想要的值的正确方法是什么?
添加这个:
const postsResult = await Promise.all(posts)