Home  >  Article  >  Web Front-end  >  nodejs requests third-party interface concurrency

nodejs requests third-party interface concurrency

WBOY
WBOYOriginal
2023-05-08 14:40:112821browse

Node.js is an open and flexible JavaScript asynchronous programming language. Its powerful concurrent task processing capabilities bring unlimited possibilities to developers. Especially when requesting third-party APIs or interfaces, we often need concurrent requests to improve performance and response speed. Therefore, this article will focus on how to request concurrent processing of third-party interfaces in Node.

1. Node.js requests third-party interface

As an open platform, Node.js can access and process HTTP, HTTPS, TCP, UDP, DNS and other network protocols. In actual development, we usually use Node.js to initiate HTTP requests, pass data to third-party interfaces, and receive return results. The most commonly used HTTP request tools in Node.js are the http and https modules.

1. Use HTTP request tool

Constructing an HTTP request usually requires specifying the request method, request header, request body and other information. In Node.js, we can construct an HTTP request in the following way:

const http = require('http');
const options = {
   hostname: 'www.example.com',
   port: 80,
   path: '/api/getdata',
   method: 'GET',
   headers: {
       'Content-Type': 'application/json',
       'Authorization': 'Bearer XXXXXXXXXXXX'
   }
};

const req = http.request(options, (res) => {
   console.log(`状态码:${res.statusCode}`);
   res.setEncoding('utf8');
   res.on('data', (chunk) => {
       console.log(`响应主体:${chunk}`);
   });
   res.on('end', () => {
       console.log('响应中已无数据。');
   });
});

req.on('error', (e) => {
   console.error(`请求遇到问题:${e.message}`);
});

// 写入数据到请求主体
req.write('{"username":"hello","password":"world"}');
req.end();

Through the http.request() method, we can create an HTTP request and use that request to communicate with the server communicate. This method contains two parameters: the first parameter specifies the request target, which includes request method, request header, request body and other information; the second parameter is a callback function used to process the response object.

2. Use the https request tool

In the HTTPS request, ciphertext needs to be transmitted, so the public key and private key need to be used. In Node.js, the https module can be used to make HTTPS requests very conveniently, as shown in the following example:

const https = require('https');
const options = {
   hostname: 'www.example.com',
   port: 443,
   path: '/api/getdata',
   method: 'GET',
   headers: {
       'Content-Type': 'application/json',
       'Authorization': 'Bearer XXXXXXXXXXXX'
   }
};

const req = https.request(options, (res) => {
   console.log(`状态码:${res.statusCode}`);
   res.setEncoding('utf8');
   res.on('data', (chunk) => {
       console.log(`响应主体:${chunk}`);
   });
   res.on('end', () => {
       console.log('响应中已无数据。');
   });
});

req.on('error', (e) => {
   console.error(`请求遇到问题:${e.message}`);
});

// 写入数据到请求主体
req.write('{"username":"hello","password":"world"}');
req.end();

2. Node.js requests third-party interface concurrent processing

In actual development, the efficiency of a single request will be relatively low, because when requesting a third-party interface, it takes a lot of time to wait for a response. Sending multiple requests at the same time can greatly improve the efficiency of data processing. In Node.js, multiple methods can be used to implement concurrent requests, such as Promise, async/await, event listening, etc.

1. Promise method

Use Promise.all() to make concurrent requests, package the request data into an array and send it out at the same time, and then wait for all requests to be responded to before processing, which can greatly improve processing efficiency. The following is a simple example to illustrate the implementation of the Promise method:

const request = require('request-promise');

//多个请求
const requests = [
   request('https://api.example.com/1'),
   request('https://api.example.com/2'),
   request('https://api.example.com/3')
];

//并发处理多个请求
Promise.all(requests)
   .then((results) => {
       console.log('所有请求完成.');
       // 处理请求结果
   })
   .catch((error) => {
       console.error(`请求错误:${error}`);
   });

2. async/await method

The async/await method is an alternative to the Promise chain, which allows the code to see It's more readable and concise. When implementing concurrent requests, we can use async/await to execute multiple requests at the same time, and wait for one of the requests to return data through Promise.race, as follows:

const request = require('request-promise');

//多个请求
const requests = [
   request('https://api.example.com/1'),
   request('https://api.example.com/2'),
   request('https://api.example.com/3')
];

//异步处理多个请求
async function getMultipleData() {
   try {
       const result = await Promise.race(requests);
       console.log(`获取数据成功:${result}`);
   } catch (error) {
       console.error(`获取数据失败:${error}`);
   }
}

getMultipleData();

3. Event implementation method

Using event listening is another way to handle concurrent requests. In Node.js, EventEmitter is the standard API for handling events. Through EventEmitter we can customize events and event triggers . The following shows an example of using EventEmitter to monitor success and error events:

const request = require('request');

const emitter = new EventEmitter();

// 多个请求
const urls = ['https://api.example.com/1', 'https://api.example.com/2', 'https://api.example.com/3'];
let counter = 0;

// 逐个请求,每个请求完成时触发success和error事件
for (let i = 0; i < urls.length; i++) {
   request(urls[i], (error, response, body) => {
       if (!error && response.statusCode === 200) {
           counter++;
           emitter.emit('success', body);
       } else {
           emitter.emit('error', error);
       }
   });
}

// 监听success和error事件
emitter.on('success', (data) => {
   console.log(data);
   // 按照计数器判断是否所有请求完成
   if (counter === urls.length) {
       console.log('所有请求完成.');
   }
});
emitter.on('error', (error) => {
   console.error(`请求遇到问题:${error}`);
});

3. Summary

As an asynchronous programming language, Node.js has powerful concurrency Processing capabilities are often used to make concurrent requests when requesting third-party APIs or interfaces to improve performance and response speed. This article focuses on how to request concurrent processing of third-party interfaces in Node.js, using Promise, async/await and event monitoring to implement concurrent requests. In actual projects, you need to choose the best way to handle concurrent requests based on actual needs to achieve the best results.

The above is the detailed content of nodejs requests third-party interface concurrency. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn