JavaScript Array.fromAsync() Method

JavaScript Tutorials


JavaScript Array.fromAsync() creates an array from an async iterable, a regular iterable, or an array-like object. The method waits for asynchronous values and returns a promise that resolves to the completed array.

You can use it when data arrives over time, such as records read from a stream, paginated results, or values produced by an async generator. It provides a direct alternative to writing a manual for await...of loop when your goal is one array.

How Array.fromAsync() Works

Array.fromAsync() reads the source from start to finish. It awaits each promised value, optionally transforms that value with a mapping function, and adds the result to a new array. The source array or iterable remains unchanged.

Input source How the method reads it
Async iterable Uses its asynchronous iterator and awaits each step
Regular iterable Reads values in order and awaits promise values
Array-like object Reads indexed values from zero up to length

Array.fromAsync() Syntax

Syntax:

// Convert a source and optionally map each resolved value.
const result = await Array.fromAsync(source, mapFunction, thisArgument);
  • source supplies the values. It can be async iterable, iterable, or array-like.
  • mapFunction is optional. It receives the current value and zero-based index.
  • thisArgument is optional. It becomes the this value inside a regular mapping function.

The method always returns a Promise. Use await inside an async function, or handle the result with then().

Convert an Async Generator to an Array

The following async generator supplies order totals one at a time. Array.fromAsync() waits for every value and formats it before returning the final array.

Example:

async function* loadOrderTotals() {
  const totals = [1200, 850, 1640];

  for (const total of totals) {
    // Simulate one asynchronous value arriving at a time.
    await Promise.resolve();
    yield total;
  }
}

async function main() {
  const formatted = await Array.fromAsync(
    loadOrderTotals(),
    (total, index) => "Order " + (index + 1) + ": Rs." + total
  );

  console.log(formatted.join("\n"));
}

main().catch(console.error);

Output:

Order 1: Rs.1200
Order 2: Rs.850
Order 3: Rs.1640

Await Promise Values

A regular iterable may contain promises. Array.fromAsync() awaits them before it stores their values. This differs from Array.from(), which places the promise objects themselves in the new array.

Example:

const scores = [Promise.resolve(72), Promise.resolve(88)];

// Wait for both values before creating the final array.
const resolvedScores = await Array.fromAsync(scores);
console.log(resolvedScores);

Output:

[72, 88]

Use an Asynchronous Mapping Function

The mapping function may also return a promise. Array.fromAsync() awaits that result before moving to the next item. This behavior helps when each transformation depends on asynchronous work.

Example:

const productIds = [101, 102, 103];

const labels = await Array.fromAsync(productIds, async (id) => {
  // Replace this resolved promise with an API or database lookup.
  const name = await Promise.resolve("Product " + id);
  return name;
});

console.log(labels);

Sequential Processing and Promise.all()

Array.fromAsync() consumes an async iterable sequentially. It requests the next item only after the current step finishes. That controlled pace works well with streams and sources that apply backpressure.

Approach Best use Processing style
Array.fromAsync() Async iterables and ordered, paced work Generally sequential
Promise.all() An existing collection of independent promises Starts work concurrently

Note: Do not replace Promise.all() automatically. If independent tasks should run together for speed, Promise.all() usually expresses that intent more clearly.

Handle Rejected Values

If iteration, an awaited value, or the mapping function fails, the returned promise rejects. Catch the error around the awaited call.

Example:

async function collectNames(source) {
  try {
    // A rejected item stops the conversion.
    return await Array.fromAsync(source);
  } catch (error) {
    console.error("Could not collect names:", error.message);
    return [];
  }
}

When to Use Array.fromAsync()

  • Collect all values from an async generator into one array.
  • Resolve promised items from an iterable while preserving their order.
  • Apply an awaited transformation during collection.
  • Read an async source at a controlled, sequential pace.

Avoid collecting an unbounded stream because the array keeps every value in memory. Process very large or endless streams item by item instead. For production browser code, also check the support requirements of your target users.

Conclusion

Array.fromAsync() gives you a concise way to turn asynchronous data into a normal JavaScript array. It accepts several source types, awaits values and mapping results, preserves order, and reports failures through its returned promise. Choose it when you need the complete result in memory and sequential collection matches the task.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram