如何在Node.js中结合Request使用Promise.all发起批量请求?
request Got it, let's translate that browser-side fetch + Promise.all pattern to Node.js using the request library. First, a quick heads-up: the original request package is deprecated now, but since you specifically asked for it, we'll focus on that first—plus a quick note on modern alternatives at the end.
Step 1: Wrap request in a Promise
The core issue is that request uses callbacks by default, not Promises. So we need a helper function to convert it into a Promise-based API, just like how fetch works in the browser.
const request = require('request'); // Helper function to make a request and return parsed JSON as a Promise function fetchJson(url) { return new Promise((resolve, reject) => { request(url, (error, response, body) => { // Handle request-level errors (e.g., network issues) if (error) { return reject(error); } // Check if the response was successful if (response.statusCode < 200 || response.statusCode >= 300) { return reject(new Error(`Request failed with status ${response.statusCode}`)); } // Parse the JSON body (and handle parsing errors) try { const jsonData = JSON.parse(body); resolve(jsonData); } catch (parseError) { reject(parseError); } }); }); }
Step 2: Use Promise.all for Parallel Requests
Now that we have our Promise-based helper, we can use Promise.all exactly like you did in React:
// Define your target URLs const url1 = 'https://api.example.com/data1'; const url2 = 'https://api.example.com/data2'; const url3 = 'https://api.example.com/data3'; const url4 = 'https://api.example.com/data4'; // Run all requests in parallel Promise.all([ fetchJson(url1), fetchJson(url2), fetchJson(url3), fetchJson(url4) ]) .then(([data1, data2, data3, data4]) => { // Destructure responses directly (cleaner than index access) console.log('All data received:'); console.log('Data 1:', data1); console.log('Data 2:', data2); // Add your custom data processing logic here }) .catch(error => { // Handle any failed request (Promise.all rejects immediately if any promise fails) console.error('Error in one of the requests:', error.message); });
A Note on Modern Alternatives
Since request is deprecated, you might want to switch to libraries that support Promises natively, like axios or node-fetch (which works almost identically to browser fetch):
For example, with node-fetch, your code would look nearly identical to your React version:
const fetch = require('node-fetch'); Promise.all([ fetch(url1).then(res => res.json()), fetch(url2).then(res => res.json()), fetch(url3).then(res => res.json()), fetch(url4).then(res => res.json()) ]) .then(([data1, data2, data3, data4]) => { // Process your data here }) .catch(error => console.error(error));
This avoids manually wrapping the library in Promises, which is cleaner and less error-prone.
内容的提问来源于stack exchange,提问作者Shai UI

