-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample09.ts
More file actions
75 lines (64 loc) · 2.15 KB
/
example09.ts
File metadata and controls
75 lines (64 loc) · 2.15 KB
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
interface ExchangeRate {
date: string;
usd: {
currency: string;
purchaseRate: number;
saleRate: number;
};
}
interface AsyncCommand<T = any> {
execute(): Promise<T>;
}
class FetchExchangeRateCommand implements AsyncCommand<ExchangeRate> {
constructor(private date: string) { }
async execute(): Promise<ExchangeRate> {
const url = `https://api.privatbank.ua/p24api/exchange_rates?json&date=${this.date}`;
const response = await fetch(url);
const data = await response.json();
const usd = data.exchangeRate.find((rate: any) => rate.currency === "USD");
if (!usd) {
throw new Error(`Курс USD відсутній для дати ${this.date}`);
}
return { date: this.date, usd };
}
}
type CommandResult<T> = {
index: number;
status: "success" | "error";
data?: T;
error?: string;
}
async function runParallel<T extends AsyncCommand<R>, R>(commands: T[]): Promise<CommandResult<R>[]> {
const results = await Promise.allSettled(commands.map(cmd => cmd.execute()));
return results.map((result, index): CommandResult<R> => {
if (result.status === "fulfilled") {
return {
index,
status: "success",
data: result.value
};
}
return {
index,
status: "error",
error: result.reason instanceof Error ? result.reason.message : String(result.reason)
};
});
}
// Приклад використання
const commands = [
new FetchExchangeRateCommand("20.04.2024"),
new FetchExchangeRateCommand("20.04.2025")
];
runParallel<FetchExchangeRateCommand, ExchangeRate>(commands).then(results => {
results.forEach(result => {
if (result.status === "success" && result.data) {
const { date, usd } = result.data;
console.log(
`Курс [${date}]: USD/UAH ${usd.purchaseRate.toFixed(2)}/${usd.saleRate.toFixed(2)}`
);
} else {
console.warn(`Помилка для команди ${result.index + 1}: ${result.error}`);
}
});
});