数据由数据库中不同用户发布的一系列帖子组成。每个帖子都包含发帖用户的 _id。我想映射每个帖子,获取帖子的 _id 并获取每个帖子的用户数据。这就是我取得的进展。有没有正确的方法或更好的方法?我遇到了错误。
const getUsers = () => {
data.map(async () => {
await axios({
method: "POST",
withCredentials: true, url:`https://droplikebackend.herokuapp.com/api/user/get/${id}`,
data: {
userId: data.userId,
},
})
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
});
};
最佳答案
最好的方法是在单独的函数中提取确切的 getUser
逻辑。我不确定的是为什么方法是“POST”以及为什么用户的 id 在 axios 的 URL 和数据属性中。
如您所见,不需要 .then 和 .catch,但如果您想捕获某些东西 - 只需使用普通的 try/catch block ,不要将 async/await 与 .then.catch 混合使用:
const getUser = async (userId) => {
const response = await axios({
method: "POST",
withCredentials: true,
url: `https://droplikebackend.herokuapp.com/api/user/get/${userId}`,
data: { userId: userId }
});
return response.data;
};
现在关于用法 - 如您所见,本例中的 map 函数将返回一个 Promise 数组,您可以使用 Promise.all()
方法等待它们并获得结果.如果它是一个带有等待的 for 循环,所有的 promise 都会模拟地触发,而不是一个一个地触发。缺点:如果您的 API 具有速率限制器 - 您可能会被禁止一段时间,因为对于 100 个帖子,将在不到一秒内触发 100 个 getUser 请求。
const getUsers = async () => {
const uniqueUserIds = [...new Set(data.map((x) => x.userId))];
const promises = uniqueUserIds.map(getUser);
const users = await Promise.all(promises);
return users;
};
关于javascript - 是否可以通过数组进行映射并从服务器获取从映射数组中获取的每个项目的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73347095/