TypeScript example

How to use async/await with Array.map in TypeScript

8 min read Updated Nov 2026 Runs in an isolated runtime
Quick answer

Wrap the map in Promise.all: const users = await Promise.all(ids.map((id) => fetchUser(id)));. An async callback makes map return Promise<User>[]; Promise.all turns that into one Promise<User[]>, and await gives you a User[] in the original order. Writing await ids.map(…) without it awaits nothing, which is why TypeScript reports Type 'Promise<number>[]' is not assignable to type 'number[]'.

Array.prototype.map is synchronous. It calls your callback once per element and collects whatever comes back. When the callback is async, what comes back is a promise, so the result is an array of promises, and await only waits for a promise, not for an array of them. TypeScript tracks this precisely: the type of the map is Promise<T>[], the type of Promise.all on it is Promise<T[]>, and the checker stops you when you use one where the other belongs.

Below: the Promise.all pattern, what goes wrong without it, how to run the calls one at a time instead, the forEach and filter traps, handling failures, and capping how many calls run at once. The examples use timers in place of real network calls, and each one runs on this page: hit Run, then edit the code and run it again.

1await Promise.all(items.map(async …))Recommended

map starts every call straight away, without waiting for the previous one, and hands you the promises. Promise.all waits until all of them have resolved and resolves to their values, in the same order as the input, whichever call finishes first. The types follow along with no annotation needed: fetchUser returns Promise<User>, so the map is Promise<User>[] and the awaited result is User[]. The : User[] on users is there only to show it. When the callback does more than one call, make it async and annotate its return type if you want the checker to hold you to it.

promise-all.ts
interface User {
    id: number;
    name: string;
}

const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));

// Stands in for a database or HTTP call; later ids answer first
async function fetchUser(id: number): Promise<User> {
    await sleep(40 - id * 10);
    console.log(`loaded user ${id}`);
    return { id, name: `user-${id}` };
}

async function main() {
    const ids = [1, 2, 3];

    // map starts every call at once: Promise<User>[]
    const pending = ids.map((id) => fetchUser(id));
    // Promise.all waits for all of them: Promise<User[]>, so await gives User[]
    const users: User[] = await Promise.all(pending);
    console.log(users.map((u) => u.name));

    // The usual one-liner, with an async callback that does more work
    const labels = await Promise.all(
        ids.map(async (id): Promise<string> => {
            const user = await fetchUser(id);
            return `${user.id}:${user.name.toUpperCase()}`;
        }),
    );
    console.log(labels);
}

main();

Output

The users load in reverse (loaded user 3 first, because its fake call is the shortest), yet the result is [ 'user-1', 'user-2', 'user-3' ]: Promise.all puts each value at its input's index. The second run prints [ '1:USER-1', '2:USER-2', '3:USER-3' ] the same way. All three calls ran at the same time, so the whole map takes about as long as the slowest call, not the sum. The calls start inside map, not inside Promise.all, which only waits. If one call throws, Promise.all rejects; section 5 covers that.

2Why await items.map(…) gives you promises

This is the code the question usually starts from: await in front of the map, hoping it waits for every callback. await on a value that is not a promise (an array is not) returns the value as it is, after one tick. So the array still holds promises, still pending, and TypeScript infers results as Promise<number>[]. At runtime nothing throws until you call a number method on an element; in TypeScript, the first use already fails to compile.

the-mistake.ts
async function double(n: number): Promise<number> {
    return n * 2;
}

async function main() {
    const nums = [1, 2, 3];

    // An async callback returns a promise, so map returns Promise<number>[]
    // and awaiting an array (not a promise) hands back the same array
    const results = await nums.map(async (n) => double(n));
    console.log(results);
    console.log(results[0] instanceof Promise);

    // Promise.all turns Promise<number>[] into Promise<number[]>
    const values = await Promise.all(nums.map(async (n) => double(n)));
    console.log(values);
    console.log(values[0] + 1);
}

main();

Output

The first line is [ Promise { <pending> }, Promise { <pending> }, Promise { <pending> } ] and results[0] instanceof Promise is true. With Promise.all you get [ 2, 4, 6 ], and values[0] + 1 is 3. Annotate the broken version as the question does, const results: number[] = await nums.map(async (n) => double(n));, and the compiler stops with error TS2322: Type 'Promise<number>[]' is not assignable to type 'number[]'. followed by Type 'Promise<number>' is not assignable to type 'number'. Without the annotation, the error moves to the first use: results[0].toFixed(1) gives error TS2339: Property 'toFixed' does not exist on type 'Promise<number>'. Both messages are the hint to add Promise.all, not to cast.

3One at a time: for...of with await

Sometimes the calls must not overlap: each write depends on the previous one, an API allows one request at a time, or the order of side effects matters. Then don't use map at all. A for...of loop with await inside an async function pauses on each element before starting the next, and you push the results into an array you typed yourself. Array.fromAsync(items, fn) (ES2024, typed in TypeScript's ESNext lib) does the same as an expression and returns Promise<string[]> here.

sequential.ts
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));

async function save(item: string): Promise<string> {
    console.log(`start ${item}`);
    await sleep(10);
    console.log(`end ${item}`);
    return `${item}:saved`;
}

async function main() {
    const items = ["a", "b", "c"];

    // One at a time: each call finishes before the next one starts
    const results: string[] = [];
    for (const item of items) {
        results.push(await save(item));
    }
    console.log(results);

    // Array.fromAsync (ES2024) also awaits each mapped value in turn
    const again = await Array.fromAsync(items.slice(0, 2), (item) => save(item));
    console.log(again);
}

main();

Output

Every start is followed by its own end before the next start: start a, end a, start b, and so on, and the result is [ 'a:saved', 'b:saved', 'c:saved' ]. Array.fromAsync shows the same interleaving. In the Promise.all version all the start lines would come first. The cost is time: the loop takes the sum of all the calls instead of the longest one, so use it only when the order or the load really calls for it. Array.fromAsync needs Node 22 or later and ES2024 (or ESNext) in lib.

4forEach and filter don't wait for async callbacks

Two neighbours of map look like they should work with an async callback and don't. forEach ignores what its callback returns, so the promises are dropped and the code after it runs before any of them finish. filter keeps an element when the callback returns something truthy, and a promise is always truthy, even one that will resolve to false. TypeScript accepts both without a word: an async function fits forEach's void callback, and filter's predicate may return unknown. The lint rule @typescript-eslint/no-misused-promises is what flags them.

foreach-filter.ts
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));

async function isEven(n: number): Promise<boolean> {
    await sleep(5);
    return n % 2 === 0;
}

async function main() {
    const ids = [1, 2, 3, 4];
    const seen: number[] = [];

    // forEach throws away the promise each callback returns
    ids.forEach(async (id) => {
        await sleep(10);
        seen.push(id);
    });
    console.log("after forEach:", seen);

    // An async predicate returns a Promise, and every Promise is truthy
    const wrong = ids.filter(async (n) => isEven(n));
    console.log("filter(async):", wrong);

    // Fix: get the booleans with Promise.all, then filter by index
    const flags: boolean[] = await Promise.all(ids.map((n) => isEven(n)));
    const evens = ids.filter((_, i) => flags[i]);
    console.log("filtered:", evens);

    await sleep(50);
    console.log("50 ms later:", seen);
}

main();

Output

Right after the forEach, seen is still []; the callbacks fill it in later (50 ms later: [ 1, 2, 3, 4 ]), long after the code that needed it. filter(async …) keeps everything, [ 1, 2, 3, 4 ]. The fix computes the answers first with Promise.all and a map, then filters synchronously by index: [ 2, 4 ]. For forEach, replace it with await Promise.all(items.map(async (item) => { … })) to run in parallel, or with the for...of loop from section 3 to run in order.

5When some calls fail: Promise.allSettled

Promise.all rejects as soon as one promise rejects, with that error, and you lose the values of the calls that worked (they keep running; their results just have nowhere to go). When partial results are useful, use Promise.allSettled. It never rejects, and resolves to PromiseSettledResult<Profile>[], a union of { status: "fulfilled", value } and { status: "rejected", reason }. Checking status narrows each element, so r.value is only available in the fulfilled branch.

all-settled.ts
interface Profile {
    id: number;
    name: string;
}

async function loadProfile(id: number): Promise<Profile> {
    if (id % 2 === 0) throw new Error(`profile ${id} not found`);
    return { id, name: `user-${id}` };
}

async function main() {
    const ids = [1, 2, 3, 4];

    // Promise.all rejects with the first error, and the other results are lost
    try {
        await Promise.all(ids.map((id) => loadProfile(id)));
    } catch (err) {
        console.log("Promise.all:", err instanceof Error ? err.message : err);
    }

    // allSettled waits for every call: PromiseSettledResult<Profile>[]
    const results = await Promise.allSettled(ids.map((id) => loadProfile(id)));
    for (const r of results) {
        if (r.status === "fulfilled") {
            console.log("ok", r.value.name); // r is PromiseFulfilledResult<Profile>
        } else {
            console.log("failed", r.reason instanceof Error ? r.reason.message : r.reason);
        }
    }

    // Keep the successes: since TypeScript 5.5 the filter narrows the type
    const profiles: Profile[] = results
        .filter((r) => r.status === "fulfilled")
        .map((r) => r.value);
    console.log(profiles);
}

main();

Output

Promise.all reports only profile 2 not found. allSettled reports all four: ok user-1, failed profile 2 not found, ok user-3, failed profile 4 not found, and the filter keeps the two profiles. Since TypeScript 5.5 the checker infers (r) => r.status === "fulfilled" as a type guard, so .map((r) => r.value) compiles; on older versions write the guard out: (r): r is PromiseFulfilledResult<Profile> => r.status === "fulfilled". The err instanceof Error checks matter with strict on, as in most projects: a catch variable is then unknown, and err.message fails with error TS18046: 'err' is of type 'unknown'. (this page's compiler runs without strict, so it wouldn't complain). r.reason is typed any, so check it the same way.

6Capping how many run at once

Promise.all(items.map(fn)) starts every call at once. For 10 items that is fine; for 5,000 rows it can hit rate limits or exhaust connections. A small generic helper keeps the Promise.all types and caps the number in flight: it starts limit workers, each taking the next index until the list is done, and writes each result at its index so the order holds. The simpler alternative is batches: slice the array and run Promise.all on each slice in a loop.

with-limit.ts
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));

// Like Promise.all(items.map(fn)), but at most `limit` calls run at once
async function mapWithLimit<T, R>(
    items: readonly T[],
    limit: number,
    fn: (item: T, index: number) => Promise<R>,
): Promise<R[]> {
    const results = new Array<R>(items.length);
    let next = 0;
    // Each worker takes the next index until none are left
    async function worker(): Promise<void> {
        while (next < items.length) {
            const i = next++;
            results[i] = await fn(items[i], i);
        }
    }
    const workers = Array.from({ length: Math.min(limit, items.length) }, () => worker());
    await Promise.all(workers);
    return results;
}

let active = 0;
let peak = 0;

async function convert(file: string): Promise<string> {
    active++;
    peak = Math.max(peak, active);
    await sleep(10 + (file.charCodeAt(0) % 3) * 5); // uneven durations
    active--;
    return file.replace(".png", ".webp");
}

async function main() {
    const files = ["a.png", "b.png", "c.png", "d.png", "e.png", "f.png", "g.png"];

    const out = await mapWithLimit(files, 3, convert); // Promise<string[]>
    console.log(out.join(" "));
    console.log(`peak: ${peak} at once`);

    // Batches of 3: simpler, but each batch waits for its slowest call
    peak = 0;
    const batched: string[] = [];
    for (let i = 0; i < files.length; i += 3) {
        const batch = files.slice(i, i + 3);
        batched.push(...(await Promise.all(batch.map((f) => convert(f)))));
    }
    console.log(batched.join(" "));
    console.log(`peak: ${peak} at once`);
}

main();

Output

Both print a.webp b.webp c.webp d.webp e.webp f.webp g.webp in input order with peak: 3 at once. R is inferred from convert, so mapWithLimit(files, 3, convert) is a Promise<string[]> with no type arguments written. The difference is the idle time: the helper starts the fourth file as soon as any of the first three ends, while a batch waits for its slowest call before the next batch starts. Packages such as p-limit and p-map do the same; the helper is enough when you don't want a dependency.

7Which should you use?

PatternRunsResult typeBest for
await Promise.all(items.map(fn))All at onceT[], rejects on first errorMost async maps
for (const x of items) await fn(x)One at a timeThe array you buildOrder-dependent work, strict rate limits
await Array.fromAsync(items, fn)One at a timeT[]The same, as an expression
await Promise.allSettled(items.map(fn))All at oncePromiseSettledResult<T>[]Keeping partial results
mapWithLimit(items, n, fn)n at a timeT[]Large lists, rate-limited APIs
await items.map(fn) / forEach(async …)Not awaitedPromise<T>[] / voidNever: nothing waits

Frequently asked questions

How do I fix "Type 'Promise<number>[]' is not assignable to type 'number[]'"?

Wrap the map in Promise.all and await that: const results: number[] = await Promise.all(nums.map(async (n) => double(n)));. await nums.map(…) awaits an array, which is not a promise, so you get the array of promises back ([ Promise { <pending> }, … ]). Casting is no way out: as number[] fails with error TS2352: Conversion of type 'Promise<number>[]' to type 'number[]' may be a mistake because neither type sufficiently overlaps with the other., and forcing it through unknown compiles while the values stay promises.

Does Promise.all keep the results in the same order as the array?

Yes. Each value lands at its input's index, whatever order the calls finish in. In the first example the users load as 3, 2, 1, and the result is still [ 'user-1', 'user-2', 'user-3' ]. The same goes for Promise.allSettled.

Does Promise.all run the calls in parallel?

It does not start them; map does, when it calls your async callback for each element. Promise.all only waits for the promises it is given. The calls then overlap while they wait on I/O or timers, so the total time is about that of the slowest call. CPU-bound work in the callbacks still runs one piece at a time on the single JavaScript thread.

How do I await several different calls and keep each type?

Pass a tuple instead of a mapped array: const [user, orders] = await Promise.all([getUser(1), getOrders(1)]);. TypeScript types the result as [User, Order[]], so user is a User and orders is an Order[], not a union of both. The calls run at the same time, as with map.

Can I use async/await with reduce?

Yes, if the accumulator is a promise you await at the top of each step: await ids.reduce(async (accP: Promise<number>, id) => { const acc = await accP; … return acc + x; }, Promise.resolve(0)). It runs the steps one at a time, like a for...of loop, which is usually easier to read. For a sum of independent calls, Promise.all and a plain reduce over the results is faster.

How do I get the element type from an async function's return type?

Use Awaited to unwrap the promise: for getOrders(): Promise<Order[]>, Awaited<ReturnType<typeof getOrders>> is Order[] and adding [number] gives Order. Promise.all uses Awaited itself to type its result. See how to get the return type of a function for ReturnType, Parameters and Awaited in more depth.

Run it yourself

Open any of these in the full TypeScript editor to tweak, run and share.

TypeScript playground