Home > Article > Web Front-end > nodejs sends multiple http requests
With the development of the Internet, technological advancement, and the continuous emergence of Internet applications, people have more and more demands for network communications. Among these network communications, the http protocol is the most common method. In nodejs, we can easily send http requests to achieve network communication. This article will introduce how to send multiple http requests using nodejs.
In nodejs, the http module is a module used to handle the http protocol. It provides some practical APIs to create HTTP servers and clients. Handle incoming HTTP requests, as well as send HTTP requests.
You can use two methods to send http requests using the http module:
We know that asynchronous programming is a very common programming method in nodejs, so we can use Promise to make multiple http requests asynchronously programming.
Promise is an object that represents future results, and Promise itself is a constructor that receives a function parameter. The function has two parameters: resolve and reject, which represent success and failure callback functions respectively.
The advantage of using Promise is that it can solve the callback hell problem and make the code more readable and maintainable.
The async/await syntax sugar introduced in ES6 allows us to implement asynchronous programming without using Promise, making the code more concise and clear .
async/await actually simplifies and encapsulates Promise, using the async keyword to declare an asynchronous function, and then using the await keyword to wait for the result of the asynchronous operation, so that the execution of the program can be in order to avoid the problem of callback hell.
Below we will use Promise and async/await to send multiple http requests.
We assume that we want to initiate http requests to multiple websites and merge the results returned by these websites together.
We first create an array to store the target url and request method of these requests (here we use the GET method), as shown below:
const targets = [ {url: 'https://www.baidu.com', method: 'GET'}, {url: 'https://www.google.com', method: 'GET'}, {url: 'https://www.bing.com', method: 'GET'}, ];
Then, we define a function that receives A target url and request method, and returns a Promise object for sending http requests and processing responses. The implementation of the function is as follows:
const http = require('http'); function sendRequest(target) { return new Promise((resolve, reject) => { const req = http.request(target, res => { let result = ''; res.setEncoding('utf8'); res.on('data', chunk => { result += chunk; }); res.on('end', () => { resolve(result); }); }); req.on('error', err => { reject(err); }); req.end(); }); }
In the above function, we use the http.request method to send an http request and receive the response data through the res.on('data', ...) event handling function , use the res.on('end', ...) event processing function to process the logic after the response ends, and finally return the received response data as the result of Promise.
We can use the following code to test whether this function is working properly.
sendRequest({url: 'https://www.baidu.com', method: 'GET'}) .then(result => { console.log(result); }) .catch(err => { console.error('An error occurred:', err); });
We can now define a function that receives multiple target urls and request methods and returns a Promise object for sending multiple http requests and merging their results together. The implementation of the function is as follows:
function sendMultiRequests(targets) { return Promise.all(targets.map(target => { return sendRequest(target); })); }
In the above function, we use the Promise.all method to encapsulate multiple Promise objects into a new Promise object. When all current Promise are successful, the returned Promise is successful. If any Promise fails, the returned Promise will fail.
We can now use this function to send multiple http requests and merge their results together.
sendMultiRequests(targets) .then(results => { console.log('All requests completed.'); console.log('Results:'); console.log(results); }) .catch(err => { console.error('An error occurred:', err); });
When all http requests are completed, we merge their results together and print them out.
In ES6, we can use async/await syntax to implement asynchronous programming. We can implement the above code using async/await. The core of this implementation is to encapsulate Promise as an async function and use the await keyword to wait for the completion of asynchronous operations.
The following is an example of using async/await to send multiple http requests.
async function sendRequests(targets) { const results = await Promise.all(targets.map(async target => { const result = await sendRequest(target); return result; })); return results; }
In the above code, we define an async function sendRequests to send multiple http requests and wait for their results. The Promise.all method returns a Promise object. When all Promises succeed, the returned Promise will succeed. If any Promise fails, the returned Promise will fail. We use the await keyword to wait for the completion of the Promise object and directly assign the result to the results array.
We can use the following code to test whether this async function is working properly.
sendRequests(targets) .then(results => { console.log('All requests completed.'); console.log('Results:'); console.log(results); }) .catch(err => { console.error('An error occurred:', err); });
When all http requests are completed, we merge their results together and print them out.
This article introduces two ways to send multiple http requests using nodejs. The first way is to use Promise to send multiple http requests and merge their results together. The second way is to use async/await syntax sugar to send multiple http requests and wait for their results. Whether you use Promise or async/await, you can easily implement asynchronous programming of multiple http requests, making the code more readable and maintainable.
The above is the detailed content of nodejs sends multiple http requests. For more information, please follow other related articles on the PHP Chinese website!