-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathhikerBatchFetch.js
84 lines (71 loc) · 2.74 KB
/
hikerBatchFetch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import DsQueue from './dsQueue.js';
import fastq from "fastq";
import axios from 'axios';
export const batchFetch3 = async (items, maxWorkers = 5, timeoutConfig = 5000) => {
let t1 = (new Date()).getTime();
// 获取全局 timeout 设置
const timeout = timeoutConfig;
// 创建任务处理函数
const worker = async (task, callback) => {
const {item, index, results} = task;
try {
const response = await axios(
Object.assign({}, item?.options, {
url: item.url,
method: item?.options?.method || 'GET',
timeout: item?.options?.timeout || timeout,
responseType: 'text',
}),
);
results[index] = response.data; // 保存结果
callback(null); // 通知任务成功完成
} catch (error) {
console.log(`[batchFetch][error] ${item.url}: ${error}`);
results[index] = null; // 记录错误
callback(null); // 即使出错,也调用回调,不中断任务队列
}
};
// 创建 fastq 队列
const results = [];
const queue = fastq(worker, maxWorkers);
// 将任务添加到队列,并捕获错误以确保继续执行
const tasks = items.map((item, index) => {
return new Promise((resolve) => {
queue.push({item, index, results}, () => resolve());
});
});
// 等待所有任务完成
await Promise.all(tasks);
let t2 = (new Date()).getTime();
log(`fastq 批量请求 ${items[0].url} 等 ${items.length}个地址 耗时${t2 - t1}毫秒:`);
return results;
};
export const batchFetch4 = async (items, maxWorkers = 5, timeoutConfig = 5000) => {
let t1 = (new Date()).getTime();
const queue = new DsQueue(maxWorkers);
// 获取全局 timeout 设置
const timeout = timeoutConfig;
const results = [];
items.forEach((item, index) => {
queue.add(async () => {
try {
const response = await axios(
Object.assign({}, item?.options, {
url: item.url,
method: item?.options?.method || 'GET',
timeout: item?.options?.timeout || timeout,
responseType: 'text',
}),
);
results[index] = response.data;
} catch (error) {
console.log(`[batchFetch][error] ${item.url}: ${error}`);
results[index] = null;
}
});
});
await queue.onIdle();
let t2 = (new Date()).getTime();
log(`DsQueue 批量请求 ${items[0].url} 等 ${items.length}个地址 耗时${t2 - t1}毫秒:`);
return results;
};