You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

原生JS中基于fetchData实现特定类型用户多API调用的优化问询

Efficiently Fetch All Users for a Specific Type with Vanilla JS

Great question—making sequential requests for each user after fetching the type list is a common anti-pattern that slows down your app and wastes resources. Let's fix this with modern vanilla JavaScript features that let you fetch all user data in parallel.

Why Sequential Requests Are a Problem

  • Slow load times: You wait for each user request to finish before starting the next. If you have 50 users, that's 50 separate round trips stacked on top of each other.
  • Higher risk of rate limiting: Many APIs restrict how many requests you can make in a window—sequential calls eat through that quota faster.
  • Poor user experience: Your users wait longer to see the full list of users.

The Better Approach: Parallel Requests with Promise.all()

Instead of waiting for one user request to complete, we can kick off all user API calls at the same time using Promise.all(). Here's a complete implementation:

async function fetchAllUsersForType(typeId) {
  try {
    // Step 1: Fetch the user type data to get the list of user APIs
    const typeResponse = await fetch(`https://example.com/api/userType/${typeId}/`);
    if (!typeResponse.ok) throw new Error(`Failed to fetch user type: ${typeResponse.status}`);
    
    const typeData = await typeResponse.json();
    const userApiUrls = typeData.users;

    if (!userApiUrls || userApiUrls.length === 0) {
      console.log("No users found for this type");
      return [];
    }

    // Step 2: Fetch all user data in parallel
    const userPromises = userApiUrls.map(url => 
      fetch(url)
        .then(res => {
          if (!res.ok) throw new Error(`Failed to fetch user: ${res.status}`);
          return res.json();
        })
    );

    // Wait for all user requests to complete
    const allUsers = await Promise.all(userPromises);
    return allUsers;

  } catch (error) {
    console.error("Error fetching data:", error);
    // Handle the error appropriately (e.g., show a message to the user)
    return [];
  }
}

// Usage example:
fetchAllUsersForType(1)
  .then(users => {
    console.log("All users fetched:", users);
    // Render your users here
  });

Handling Partial Failures

If you want to avoid losing all user data if one request fails, use Promise.allSettled() instead of Promise.all(). This lets you process successful requests even if some fail:

// Replace the Promise.all section with this:
const userResults = await Promise.allSettled(userPromises);

// Filter out failed requests and extract successful user data
const successfulUsers = userResults
  .filter(result => result.status === "fulfilled")
  .map(result => result.value);

console.log(`Fetched ${successfulUsers.length} out of ${userApiUrls.length} users`);
return successfulUsers;

Key Takeaways

  • Parallel requests cut down total load time: All user APIs are fetched at the same time, so total time is roughly equal to the slowest single request (not the sum of all requests).
  • Error handling is critical: Always check response.ok to catch HTTP errors, and use try/catch blocks to handle network issues.
  • Promise.allSettled() is safer for partial success: Use it when you need to display whatever data you can get, even if some requests fail.

内容的提问来源于stack exchange,提问作者Jamie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:37:26