Skip to content

Latest commit

 

History

History
48 lines (35 loc) · 1.77 KB

File metadata and controls

48 lines (35 loc) · 1.77 KB

prefer-array-from-async

📝 Prefer Array.fromAsync() over for await…of array accumulation.

💼🚫 This rule is enabled in the ✅ recommended config. This rule is disabled in the ☑️ unopinionated config.

🔧 This rule is automatically fixable by the --fix CLI option.

Prefer Array.fromAsync() over simple for await…of loops that only accumulate values into an array.

Array.fromAsync(iterable) directly creates an array from an async iterable, sync iterable, or array-like value. It is clearer than manually creating an empty array, iterating with for await…of, and pushing one value per iteration.

This rule only reports adjacent const or let empty-array declarations followed by a for await…of loop with a single identifier binding and a body that is only a single result.push(…) expression. Mapped values are only reported when the pushed value is explicitly awaited, because Array.fromAsync() awaits mapper results.

Examples

// ❌
const result = [];
for await (const element of iterable) {
	result.push(element);
}

// ✅
const result = await Array.fromAsync(iterable);
// ❌
const result = [];
for await (const element of iterable) {
	result.push(await transform(element));
}

// ✅
const result = await Array.fromAsync(iterable, element => transform(element));
// ✅
const result = [];
for await (const element of iterable) {
	result.push(transform(element));
}