All files / async / unstable_all_keyed.ts

100.00% Branches 2/2
100.00% Functions 3/3
100.00% Lines 30/30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
 
 
 
 
 
 
x20
x20
x20
x20
 
x20
x20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x5
x5
 
x12
x12
 
x12
x11
x11
x19
x19
x11
x12
x12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x5
x5
 
x8
x8
 
x8
x8
x8
x14
 
 
x14
x8
x8
x8






















































































































































































// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.

// TC39 spec uses [[OwnPropertyKeys]] (Reflect.ownKeys) then filters for enumerable.
// This equivalent is faster on V8: Object.keys returns only enumerable string keys,
// so we only need to filter symbol keys for enumerability. See also assert/equal.ts.
function getEnumerableKeys(obj: object): PropertyKey[] {
  const stringKeys = Object.keys(obj);
  const symbolKeys = Object.getOwnPropertySymbols(obj).filter((key) =>
    Object.prototype.propertyIsEnumerable.call(obj, key)
  );
  return [...stringKeys, ...symbolKeys];
}

/**
 * A record type where values can be promise-like (thenables) or plain values.
 *
 * @typeParam T The base record type with resolved value types.
 */
export type PromiseRecord<T extends Record<PropertyKey, unknown>> = {
  [K in keyof T]: PromiseLike<T[K]> | T[K];
};

/**
 * A record type where values are {@linkcode PromiseSettledResult} objects.
 *
 * @typeParam T The base record type with resolved value types.
 */
export type SettledRecord<T extends Record<PropertyKey, unknown>> = {
  [K in keyof T]: PromiseSettledResult<T[K]>;
};

/**
 * Resolves all values in a record of promises in parallel, returning a promise
 * that resolves to a record with the same keys and resolved values.
 *
 * This is similar to {@linkcode Promise.all}, but for records instead of arrays,
 * allowing you to use named keys instead of positional indices.
 *
 * If any promise rejects, the returned promise immediately rejects with the
 * first rejection reason. The result object has a null prototype, matching the
 * TC39 specification.
 *
 * This function implements the behavior proposed in the TC39
 * {@link https://github.com/tc39/proposal-await-dictionary | Await Dictionary}
 * proposal (`Promise.allKeyed`).
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @typeParam T The record shape with resolved (unwrapped) value types. For
 * example, if passing `{ foo: Promise<number> }`, `T` would be `{ foo: number }`.
 * @param record A record where values are promise-like (thenables) or plain values.
 * @returns A promise that resolves to a record with the same keys and resolved
 * values. The result has a null prototype.
 * @throws Rejects with the first rejection reason if any promise in the record
 * rejects.
 *
 * @example Basic usage
 * ```ts
 * import { allKeyed } from "@std/async/unstable-all-keyed";
 * import { assertEquals } from "@std/assert";
 *
 * const result = await allKeyed({
 *   foo: Promise.resolve(1),
 *   bar: Promise.resolve("hello"),
 * });
 *
 * assertEquals(result, { foo: 1, bar: "hello" });
 * ```
 *
 * @example Parallel HTTP requests
 * ```ts no-assert ignore
 * import { allKeyed } from "@std/async/unstable-all-keyed";
 *
 * const { user, posts } = await allKeyed({
 *   user: fetch("/api/user").then((r) => r.json()),
 *   posts: fetch("/api/posts").then((r) => r.json()),
 * });
 * ```
 *
 * @example Mixed promises and plain values
 * ```ts
 * import { allKeyed } from "@std/async/unstable-all-keyed";
 * import { assertEquals } from "@std/assert";
 *
 * const result = await allKeyed({
 *   promised: Promise.resolve(42),
 *   plain: "static",
 * });
 *
 * assertEquals(result, { promised: 42, plain: "static" });
 * ```
 */
export function allKeyed<T extends Record<PropertyKey, unknown>>(
  record: PromiseRecord<T>,
): Promise<T> {
  const keys = getEnumerableKeys(record);
  const values = keys.map((key) => record[key as keyof typeof record]);

  return Promise.all(values).then((resolved) => {
    const result = Object.create(null) as T;
    for (let i = 0; i < keys.length; i++) {
      result[keys[i] as keyof T] = resolved[i] as T[keyof T];
    }
    return result;
  });
}

/**
 * Resolves all values in a record of promises in parallel, returning a promise
 * that resolves to a record with the same keys and {@linkcode PromiseSettledResult}
 * objects as values.
 *
 * This is similar to {@linkcode Promise.allSettled}, but for records instead of
 * arrays, allowing you to use named keys instead of positional indices.
 *
 * Unlike {@linkcode allKeyed}, this function never rejects due to promise
 * rejections. Instead, each value in the result record is a
 * {@linkcode PromiseSettledResult} object indicating whether the corresponding
 * promise was fulfilled or rejected. The result object has a null prototype,
 * matching the TC39 specification.
 *
 * This function implements the behavior proposed in the TC39
 * {@link https://github.com/tc39/proposal-await-dictionary | Await Dictionary}
 * proposal (`Promise.allSettledKeyed`).
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @typeParam T The record shape with resolved (unwrapped) value types. For
 * example, if passing `{ foo: Promise<number> }`, `T` would be `{ foo: number }`.
 * @param record A record where values are promise-like (thenables) or plain values.
 * @returns A promise that resolves to a record with the same keys and
 * {@linkcode PromiseSettledResult} values. The result has a null prototype.
 *
 * @example Basic usage
 * ```ts
 * import { allSettledKeyed } from "@std/async/unstable-all-keyed";
 * import { assertEquals } from "@std/assert";
 *
 * const settled = await allSettledKeyed({
 *   success: Promise.resolve(1),
 *   failure: Promise.reject(new Error("oops")),
 * });
 *
 * assertEquals(settled.success, { status: "fulfilled", value: 1 });
 * assertEquals(settled.failure.status, "rejected");
 * ```
 *
 * @example Error handling
 * ```ts
 * import { allSettledKeyed } from "@std/async/unstable-all-keyed";
 * import { assertEquals, assertExists } from "@std/assert";
 *
 * const settled = await allSettledKeyed({
 *   a: Promise.resolve("ok"),
 *   b: Promise.reject(new Error("fail")),
 *   c: Promise.resolve("also ok"),
 * });
 *
 * // Check individual results
 * if (settled.a.status === "fulfilled") {
 *   assertEquals(settled.a.value, "ok");
 * }
 * if (settled.b.status === "rejected") {
 *   assertExists(settled.b.reason);
 * }
 * ```
 */
export function allSettledKeyed<T extends Record<PropertyKey, unknown>>(
  record: PromiseRecord<T>,
): Promise<SettledRecord<T>> {
  const keys = getEnumerableKeys(record);
  const values = keys.map((key) => record[key as keyof typeof record]);

  return Promise.allSettled(values).then((settled) => {
    const result = Object.create(null) as SettledRecord<T>;
    for (let i = 0; i < keys.length; i++) {
      result[keys[i] as keyof T] = settled[i] as PromiseSettledResult<
        T[keyof T]
      >;
    }
    return result;
  });
}