Node.js 并发请求设置:async & Promise.all() 方法
在 Node.js 中,可以使用 'async' 库或者 'Promise.all()' 方法来实现并发请求的设置。
使用 'async' 库
- 安装 'async' 库:
npm install async
- 在代码中引入 'async':
const async = require('async');
- 使用 'async.mapLimit()' 方法设置并发请求:
const urls = ['http://example.com/1', 'http://example.com/2', 'http://example.com/3'];
async.mapLimit(urls, 2, (url, callback) => {
// 发送请求
// 处理响应
callback(null, response);
}, (err, results) => {
// 处理所有请求的结果
});
使用 'Promise.all()' 方法
- 使用 'Promise.all()' 方法设置并发请求:
const urls = ['http://example.com/1', 'http://example.com/2', 'http://example.com/3'];
Promise.all(urls.map(url => {
// 发送请求
// 处理响应
return response;
})).then(results => {
// 处理所有请求的结果
}).catch(err => {
// 处理错误
});
在以上两种方式中,第一个参数都是需要请求的 URL 列表,第二个参数是最大并发数。发送请求和处理响应的部分需要根据具体需求来实现。
原文地址: https://www.cveoy.top/t/topic/ndmG 著作权归作者所有。请勿转载和采集!