Node.js 使用 async.mapLimit 并行请求后继续执行剩余请求
在 Node.js 中使用 async.mapLimit 并行发起多个请求后,可以使用 Promise.all 来等待所有请求完成,并继续执行剩余的请求。
const async = require('async');
const request = require('request');
const urls = ['http://example.com', 'http://example.org', 'http://example.net'];
async.mapLimit(urls, 2, (url, callback) => {
request(url, (err, res, body) => {
if (err) {
callback(err);
} else {
callback(null, body);
}
});
}, (err, results) => {
if (err) {
console.error(err);
} else {
console.log(results);
}
// 继续执行剩余的请求
Promise.all(urls.slice(2).map(url => new Promise((resolve, reject) => {
request(url, (err, res, body) => {
if (err) {
reject(err);
} else {
resolve(body);
}
});
}))).then(results => {
console.log(results);
}).catch(err => {
console.error(err);
});
});
在上面的示例中,使用 Promise.all 等待第三个和第四个请求完成,然后打印结果。如果请求出现错误,会在 Promise.all 的 catch 中捕获。
解释:
- 使用 async.mapLimit 并行发起多个请求,同时限制并发请求数量为 2。
- 在 async.mapLimit 的回调函数中,使用 request 发起请求。
- 使用 Promise.all 等待所有请求完成,并使用 then 和 catch 处理结果和错误。
- 使用 urls.slice(2) 获取剩余的 URL,并使用 map 将其转换为 Promise 对象。
- 使用 Promise.all 执行所有 Promise 对象,并使用 then 和 catch 处理结果和错误。
总结:
使用 async.mapLimit 和 Promise.all 可以方便地实现并行请求,并在所有请求完成后继续执行剩余的请求,提高代码效率和可读性。
原文地址: https://www.cveoy.top/t/topic/ndrC 著作权归作者所有。请勿转载和采集!