Chạy song song: Promise.all, allSettled, any, race và Array.fromAsync
Bốn combinator
| Hàm | Fulfilled khi | Rejected khi | Dùng khi |
|---|---|---|---|
Promise.all | tất cả thành công → mảng kết quả | một cái lỗi (ngay lập tức) | Cần đủ mọi kết quả |
Promise.allSettled | tất cả kết thúc (luôn fulfilled) | không bao giờ | Muốn biết từng cái thành/bại |
Promise.any | cái đầu tiên thành công | tất cả lỗi → AggregateError | Nhiều nguồn dự phòng |
Promise.race | cái đầu tiên kết thúc (dù thành hay bại) | cái đầu tiên kết thúc là lỗi | Timeout, đua |
// allSettled: gửi thông báo cho nhiều người, không để một lỗi làm hỏng cả loạt
const results = await Promise.allSettled(users.map(sendEmail));
const failed = results.filter((r) => r.status === "rejected").map((r) => r.reason);
// any: lấy từ CDN nào nhanh nhất mà vẫn thành công
const res = await Promise.any([
fetch("https://cdn1.example.com/lib.js"),
fetch("https://cdn2.example.com/lib.js"),
]);Timeout
Cách hiện đại là dùng AbortSignal.timeout (bài sau). Với Promise bất kỳ, có thể dùng race:
function withTimeout(promise, ms) {
const { promise: timeout, reject } = Promise.withResolvers();
const id = setTimeout(() => reject(new Error(`Quá ${ms}ms`)), ms);
return Promise.race([promise, timeout]).finally(() => clearTimeout(id));
}Giới hạn số tác vụ đồng thời
Promise.all(items.map(fn)) khởi động tất cả cùng lúc — 10.000 request một lúc sẽ làm sập server hoặc bị rate limit. Cần giới hạn, ví dụ chỉ 5 cái chạy song song. Bạn sẽ tự viết hàm mapLimit trong bài tập cuối chương.
for await...of — duyệt async iterable
import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";
const rl = createInterface({ input: createReadStream("access.log") });
let errors = 0;
for await (const line of rl) {
if (line.includes(" 500 ")) errors++;
}Stream của Node.js, ReadableStream của web, async generator đều là async iterable.
Array.fromAsync — ES2026
Tương tự Array.from nhưng cho async iterable (hoặc iterable chứa Promise), trả về Promise của mảng:
async function* fetchAllPages(url) {
while (url) {
const { items, next } = await (await fetch(url)).json();
yield* items;
url = next;
}
}
const allProducts = await Array.fromAsync(fetchAllPages("/api/products"));
// Có hàm map như Array.from
const names = await Array.fromAsync(fetchAllPages("/api/users"), (u) => u.name);NOTE
Array.fromAsync duyệt tuần tự (chờ từng phần tử), khác Promise.all chạy song song. Dù thuộc ES2026, nó đã có trong các trình duyệt lớn và Node.js 22+ từ trước khi chuẩn được công bố.
Comments