在Node.js中使用async/await可以轻松地进行并发的HTTP请求。下面是一个示例代码 - const axios = require('axios'); // 导入axios库来处理HTTP请求
-
- // 定义要发送的多个URL列表
- const urls = [
- 'https://api.example1.com',
- 'https://api.example2.com',
- 'https://api.example3.com'
- ];
-
- // 创建一个函数来发起并发请求
- async function concurrentRequests() {
- try {
- const responses = await Promise.all(urls.map((url) => axios.get(url))); // 同时发送所有请求
-
- // 对每个响应进行处理或打印结果
- for (let i = 0; i < responses.length; i++) {
- console.log(`Response from ${urls[i]}:`, responses[i].data);
- }
- } catch (error) {
- console.error("Error occurred while making requests:", error);
- }
- }
-
- concurrentRequests(); // 调用函数开始并发请求
复制代码
|