brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Array.fromAsync() collects an async iterable into an array

Web-Development
~/tips/tip-javascript-array-fromasync

async function* pages() {

Waits for an async iterable or list of promises and returns a normal array.

Array.from() does not wait for anything, so it is no use for an async generator or a list of promises. Array.fromAsync() is the version that does. I’d call it a niche tool, but a handy one for paged APIs.

It returns a promise for an array and awaits each value as it comes:

async function* pages() {
  for (let i = 1; i <= 3; i++) {
    const res = await fetch("https://example.com/api?page=" + i);
    yield res.json();
  }
}

const all = await Array.fromAsync(pages());

Like Array.from() it accepts a map function as the second argument, and the return value of that function is awaited too:

const sizes = await Array.fromAsync(urls, async (url) => {
  const res = await fetch(url);
  return (await res.text()).length;
});

The caveat is speed. It handles items one after another and does not ask for the next value before the current one settles. MDN shows this with five promises of 100 ms each: Array.fromAsync() needs about 500 ms, Promise.all() about 100 ms. So for a plain list of independent requests, Promise.all() is still the faster choice. Use fromAsync() when order and one-at-a-time matter, such as paged APIs, or when the source is an async iterable that Promise.all() cannot take.

It also works with synchronous iterables that contain promises. If one rejects, the returned promise rejects.

Browser support is in all major browsers since January 2024, so check your minimum Node and Safari versions if you target older ones.

Further reading: MDN: Array.fromAsync()

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link