Concurrent Requests to Third-Party APIs in Node.js
This article explains how to use Node.js's built‑in http/https modules to call third‑party APIs and demonstrates three concurrency techniques—Promise.all, async/await with Promise.race, and EventEmitter—to perform parallel requests efficiently, including code examples for constructing requests, handling responses, and error management.
Node.js, as an asynchronous JavaScript runtime, provides powerful concurrency capabilities that are especially useful when calling third‑party APIs.
Basic HTTP/HTTPS requests can be made with the built‑in http and https modules. The article shows how to configure request options, send data, and process the response using http.request() and https.request() .
<code>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();
</code> <code>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();
</code>For concurrent calls, three approaches are presented:
Using Promise.all() to launch multiple requests simultaneously and wait for all results.
Using async/await together with Promise.race() to run several requests and act on the first completed one.
Using the EventEmitter API to emit and listen for success or error events for each request.
<code>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}`);
});
</code> <code>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();
</code> <code>const request = require('request');
const EventEmitter = require('events');
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}`);
});
</code>The conclusion emphasizes that Node.js’s non‑blocking model makes it suitable for high‑performance parallel API calls, and developers should choose the method that best fits their project requirements.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.