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

如何使用JS Promises循环请求LaunchLibrary API获取全部分页数据?

Fetch All LaunchLibrary API Results Using JavaScript Promises

Here's a clean, Promise-based approach using async/await to fetch all pages of launch records until you have the complete dataset:

Step 1: Single Page Fetch Function

First, create a reusable function to fetch a single page of results with a specified offset. This includes date parameters to target the past month's launches:

async function fetchLaunchPage(offset = 0) {
  // Calculate date range for the past month
  const oneMonthAgo = new Date();
  oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
  const startDate = oneMonthAgo.toISOString().split('T')[0];
  const endDate = new Date().toISOString().split('T')[0];

  const apiUrl = `https://launchlibrary.net/1.3/launch?startDate=${startDate}&endDate=${endDate}&offset=${offset}`;
  
  const response = await fetch(apiUrl);
  
  if (!response.ok) {
    throw new Error(`Failed to fetch page: HTTP status ${response.status}`);
  }
  
  return await response.json();
}

Step 2: Fetch All Pages Iteratively

Next, create a function that fetches pages in sequence until all results are collected. An iterative approach using a while loop is easy to follow and avoids potential stack overflow issues with deep recursion:

async function getAllPastMonthLaunches() {
  let allLaunches = [];
  let currentOffset = 0;
  let hasMoreResults = true;

  while (hasMoreResults) {
    try {
      const pageData = await fetchLaunchPage(currentOffset);
      
      // Add current page's launches to our full list
      allLaunches = [...allLaunches, ...pageData.launches];
      
      // Check if there are more results to fetch
      const totalResults = pageData.total;
      const fetchedCount = currentOffset + pageData.count;
      
      hasMoreResults = fetchedCount < totalResults;
      currentOffset += pageData.count;
    } catch (error) {
      console.error('Error during fetch:', error);
      throw error; // Re-throw to let the caller handle it
    }
  }

  return allLaunches;
}

Step 3: Usage Example

Call the function and handle the results (or errors):

getAllPastMonthLaunches()
  .then(launches => {
    console.log(`Successfully fetched ${launches.length} launch records from the past month!`);
    // Process your full list of launches here
    console.log(launches);
  })
  .catch(error => {
    console.error('Failed to fetch all launches:', error);
  });

Key Notes

  • Error Handling: The code includes basic error checking for HTTP failures and propagates errors to the caller, so you can handle retries or user feedback as needed.
  • Rate Limiting: Be mindful of the LaunchLibrary API's rate limits. If you encounter issues, add a small delay between requests (e.g., await new Promise(resolve => setTimeout(resolve, 1000)) inside the loop).
  • Date Precision: The past month calculation is approximate. For exact date ranges (e.g., last 30 days instead of calendar month), adjust the date logic to subtract 30 days instead of one month.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:38:11