是否可以映射数组并从服务器获取从映射数组中获取的每个项目的数据?

cra*_*nne 2 javascript arrays reactjs axios

数据由数据库中不同用户发布的一系列帖子组成。每个帖子都包含发布帖子的用户的 _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);
        });
    });
  };
Run Code Online (Sandbox Code Playgroud)

Ser*_*nov 7

最好的方法是getUser在单独的函数中提取精确的逻辑。我不确定的是为什么方法是“POST”以及为什么用户的 id 既在 URL 中又在 axios 的数据属性中。

如您所见,不需要 .then 和 .catch,但如果您想捕获某些内容 - 只需使用普通的 try/catch 块,不要将 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;
};
Run Code Online (Sandbox Code Playgroud)

现在关于用法 - 在这种情况下,map 函数将返回一个 Promises 数组,如您所见,您可以使用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;
};
Run Code Online (Sandbox Code Playgroud)