如何实现多HTTP GET请求获取数据后执行指定回调方法?
Solution: Fetch and Aggregate Multiple Async HTTP Requests Before Callback
Hey there! Let's fix this code to properly collect all player data from the HTTP requests and run your callback only once everything's done. Here are the key issues in your current snippet and how to address them:
Key Problems to Fix
- Partial Response Handling: The
res.on('data')event emits chunks of the response, not the full JSON. You need to collect all chunks first before parsing. - Async Coordination: Since each HTTP request is asynchronous, you can't assume
returnDatais ready right after looping through players. We need to track when all requests complete.
Corrected Code
Here's the full working implementation with explanations:
function fetchPlayerStats(players, callbackMethod) { var returnData = []; var completedRequests = 0; var totalRequests = players.length; // Edge case: if no players, call callback immediately with empty data if (totalRequests === 0) { callbackMethod(null, returnData); return; } players.forEach(function(item) { var playerRequestUrl = baseUrl + '/' + platform + '/members/' + item.blazeId + '/stats'; https.get(playerRequestUrl, function(res) { var chunks = []; // Collect all response chunks as they arrive res.on('data', function(chunk) { chunks.push(chunk); }); // When full response is received res.on('end', function() { try { // Combine chunks into a single buffer, convert to string, then parse JSON var playerData = JSON.parse(Buffer.concat(chunks).toString()); returnData.push(playerData); } catch (error) { // Handle JSON parsing errors or invalid data console.error('Error processing data for player:', item.blazeId, error); return callbackMethod(error, null); } completedRequests++; // Trigger callback only when all requests are done if (completedRequests === totalRequests) { callbackMethod(null, returnData); } }); // Handle request-level errors res.on('error', function(error) { console.error('Request failed for player:', item.blazeId, error); callbackMethod(error, null); }); }); }); }
What's Changed?
- Full Response Collection: We now accumulate all response chunks and parse the complete data only when the
endevent fires, avoiding partial JSON parsing errors. - Completion Tracking: Added counters to track how many requests have finished. When the completed count matches the total number of players, we call the callback with all aggregated data.
- Error Handling: Added listeners for both response parsing errors and request failures, so you can gracefully handle issues and pass errors to your callback.
- Edge Case Handling: If the input
playersarray is empty, we immediately trigger the callback with an empty dataset to avoid hanging.
How to Use It
Call the function like this to get your aggregated player stats:
fetchPlayerStats(yourPlayersArray, function(error, statsData) { if (error) { // Handle any errors that occurred during requests console.error('Failed to fetch player stats:', error); return; } // Do something with the fully collected stats data console.log('All player stats:', statsData); });
This ensures your callbackMethod runs only after all HTTP requests have completed successfully (or an error is encountered).
内容的提问来源于stack exchange,提问作者ravibhagw
相关产品推荐
相关产品推荐

