Sub topic 3
Creating promises and wrapping callback APIs
Most of the promises you handle are returned by libraries or async functions. Sometimes the API you need still uses callbacks, events, or timers. In that case you build the promise yourself with the Promise constructor. This chapter shows how to type that constructor, how to wrap callback APIs without losing type information, and where hand-built promises go wrong.
It assumes you know Promise<T> and async/await syntax. It also assumes you can read simple generics such as Array<T> and function f<T>(x: T), and that you can narrow union types.
The constructor and its type parameter
new Promise<T>(executor) takes an executor function. TypeScript calls the executor immediately and passes it two functions:
resolve(value)settles the promise with a value of typeT(or a promise that resolves toT).reject(reason)settles it as rejected. The reason is typedany.
The type argument T is the only place where you say what the promise resolves to. The spine example is a delay:
function delay(ms: number): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(resolve, ms);
});
}Here T is void because the promise carries no value. Calling resolve() with no argument is allowed only when T is void (or includes void or undefined).
A promise settles at most once. After the first call to resolve or reject, later calls are ignored. TypeScript does not warn about this, so it is a runtime rule you have to keep in mind.
Inference: why you should name T
When the executor does not give TypeScript enough information, the type argument is inferred as unknown:
const a = new Promise((resolve) => resolve(42));
// a: Promise<unknown>
const b = new Promise<number>((resolve) => resolve(42));
// b: Promise<number>TypeScript does not look inside the executor to work out what you pass to resolve. Callers of a would have to narrow its value before using it. Always write the type argument, or annotate the return type of the enclosing function so the contextual type flows in:
function answer(): Promise<number> {
return new Promise((resolve) => resolve(42)); // T inferred as number from the return type
}The type argument also checks the arguments you give to resolve. With T = number, both of these are errors:
const p = new Promise<number>((resolve) => {
resolve("42"); // error: string is not assignable to number
resolve(); // error: expected 1 argument
});The second error is a strictness feature. A promise typed Promise<number> must never resolve with no value, because the consumer would receive undefined typed as number.
Resolving with another promise
resolve accepts T | PromiseLike<T>. If you pass a promise, the outer promise follows it, so the result is still Promise<T>, not Promise<Promise<T>>. This flattening is the same behavior that Awaited<T> models, which a later chapter covers.
const inner: Promise<string> = Promise.resolve("hello");
const outer = new Promise<string>((resolve) => resolve(inner));
// outer: Promise<string>Two static helpers create already-settled promises, and each has a distinct type:
| Expression | Type |
|---|---|
| `Promise.resolve(1)` | `Promise<number>` |
| `Promise.resolve()` | `Promise<void>` |
| `Promise.reject(new Error("x"))` | `Promise<never>` |
Promise<never> fits anywhere a Promise<T> is expected. That makes it convenient for tests and for early-exit branches.
Wrapping a callback API
Node-style callbacks take (err, result) as their last parameter. To wrap one, create a promise, call the function inside the executor, and map the callback onto resolve and reject.
import { readFile } from "node:fs";
function readText(path: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
readFile(path, "utf8", (err, data) => {
if (err) {
reject(err);
return;
}
resolve(data);
});
});
}Notice three details.
- The
returnafterrejectkeeps the code from falling through toresolve. Since a promise settles once, the extra call would be harmless, but the early return makes the intent clear and keepsdatanarrowed. - Because the encoding is
"utf8", the type declarations givedatathe typestring. Without the encoding, it would be aBuffer, and the compiler would rejectresolve(data). The type argument catches that mismatch. errisNodeJS.ErrnoException | null. A truthy check narrows it before you reject.
In real Node code you would use fs.promises.readFile or util.promisify. Writing the wrapper by hand is still worth knowing for libraries that offer neither.
A reusable wrapper
If you wrap many functions of the same shape, a generic helper saves repetition. This one handles functions that take one argument plus a Node-style callback:
type NodeCallback<T> = (err: Error | null, result?: T) => void;
function promisify1<A, T>(
fn: (arg: A, cb: NodeCallback<T>) => void,
): (arg: A) => Promise<T> {
return (arg) =>
new Promise<T>((resolve, reject) => {
fn(arg, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result as T);
}
});
});
}
function legacyDouble(n: number, cb: NodeCallback<number>): void {
setTimeout(() => {
if (Number.isNaN(n)) {
cb(new Error("not a number"));
} else {
cb(null, n * 2);
}
}, 10);
}
const doubleAsync = promisify1(legacyDouble);
// doubleAsync: (arg: number) => Promise<number>
doubleAsync(21).then((value) => console.log(value)); // 42TypeScript infers A = number and T = number from the signature of legacyDouble, so doubleAsync has a precise type without any annotation at the call site.
The result as T assertion is a small lie. The callback type marks result as optional, so the compiler sees T | undefined. The cast is safe only when the callback follows the convention that result is present whenever err is null. If a function can legitimately succeed with no value, give it T = void or model the result as T | undefined.
A fully general promisify has to handle any number of arguments and several overloads. Node's util.promisify does this with a large set of overloaded declarations, and it also honors a util.promisify.custom symbol. For your own code, one or two small wrappers are usually clearer than a variadic generic.
Wrapping events and timers
Events fire an unknown number of times, and promises settle once. A promise fits only the first occurrence. Use { once: true } so the listener removes itself:
function nextEvent(target: EventTarget, type: string): Promise<Event> {
return new Promise<Event>((resolve) => {
target.addEventListener(type, resolve, { once: true });
});
}If the event might never fire, the promise stays pending forever. That is a legal state in the type system, with no error and no warning. Combine event promises with a timeout, as shown below.
Adding a timeout
A timeout helper preserves T and rejects when too much time passes:
function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`Timed out after ${ms} ms`));
}, ms);
promise.then(
(value) => {
clearTimeout(timer);
resolve(value);
},
(error: unknown) => {
clearTimeout(timer);
reject(error);
},
);
});
}The helper clears the timer on both paths so it does not keep a Node process alive. It also does not stop the underlying work. If promise is a slow HTTP request, the request continues after the timeout. Stopping it needs cancellation, which the cancellation chapter covers with AbortSignal.
Gotchas
Errors thrown in later callbacks are not caught
If the executor throws synchronously, the promise rejects. Once the executor has returned, a throw from a later callback is not routed into the promise:
function broken(): Promise<number> {
return new Promise<number>((resolve) => {
setTimeout(() => {
throw new Error("boom"); // not a rejection: this is an uncaught exception
}, 10);
resolve(1);
});
}Inside any asynchronous callback, catch errors yourself and call reject. The compiler cannot detect this mistake, because a throw has no effect on types.
Do not wrap what is already a promise
This is a common mistake:
async function getName(id: number): Promise<string> {
return new Promise<string>((resolve, reject) => {
fetchUser(id).then((u) => resolve(u.name)).catch(reject);
});
}
declare function fetchUser(id: number): Promise<{ name: string }>;It works but adds noise, and it is easy to forget the reject path. Use async/await instead, which converts throws and rejections for you:
async function getNameSimple(id: number): Promise<string> {
const user = await fetchUser(id);
return user.name;
}
declare function fetchUser(id: number): Promise<{ name: string }>;Reserve new Promise for the boundary between callback-style code and promise-style code.
The async executor trap
Do not write new Promise(async (resolve, reject) => { ... }). If the async executor throws after an await, the error rejects the executor's own hidden promise, which nobody handles, and your outer promise never settles. Linters flag this with the no-async-promise-executor rule.
Rejection reasons are untyped
reject accepts any, and Promise<T> has no slot for an error type. Consumers see the error as unknown in a catch clause. If you want a specific error type, document it, throw Error subclasses, and narrow with instanceof where the error is caught. The next chapters cover that handling.
Summary of rules
| Situation | What to do |
|---|---|
| Building a promise by hand | Pass the type argument, or annotate the return type |
| Promise with no value | Use `Promise<void>` and call `resolve()` |
| Callback with `(err, result)` | Reject on `err`, resolve otherwise, return early |
| Event that may fire once | Use `{ once: true }` and add a timeout |
| Already holding a promise | Use `async`/`await` instead of `new Promise` |
| Need to stop the underlying work | Accept an `AbortSignal` (next chapters) |
Exercise
This code compiles, but n has type unknown at the call site. What is wrong, and what is the fix?
const ready = new Promise((resolve) => resolve(10));
const n = await ready;
Show answer
TypeScript does not infer the promise's type argument from what the executor passes to resolve, so it falls back to unknown. Name the type argument: new Promise<number>((resolve) => resolve(10)). Then ready is Promise<number> and n is number.
Exercise
Write a function sleepThen<T>(ms: number, value: T): Promise<T> that resolves with value after ms milliseconds. Why must T appear in both the parameter and the return type?
Show answer
function sleepThen<T>(ms: number, value: T): Promise<T> { return new Promise<T>((resolve) => { setTimeout(() => resolve(value), ms); }); }. T links the type of the input value to the type the promise resolves with. Without it, you would have to return Promise<unknown> or use any, and callers would lose the type of the result.