Sub topic 3
Creating Promises and Wrapping Callback APIs
This chapter assumes you know basic TypeScript types, generics, union types, and JavaScript callbacks, promises, and async/await.
Many older JavaScript APIs use callbacks. A callback is a function that another function calls later with a result. TypeScript can describe these APIs, but modern code is often easier to compose when the callback API is wrapped in a Promise<T>.
Constructing a promise
Promise<T> represents a future operation that eventually produces a value of type T or fails.
The Promise constructor receives an executor function. The executor receives two functions:
resolve(value)marks the operation as successful.reject(error)marks the operation as failed.
The type argument describes the successful value:
function delay(ms: number): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(resolve, ms);
});
}
async function main(): Promise<void> {
await delay(500);
console.log("Finished");
}
void main();This promise resolves with no value, so its type is Promise<void>. If the operation produced a string, the type would be Promise<string>.
A promise can settle only once. A second call to resolve or reject has no effect on the promise's state. However, code after that call still runs, so callbacks should avoid continuing after completion when duplicate calls are possible.
Wrapping an error-first callback
A common callback convention uses the first parameter for an error and the second parameter for the successful value. The error is null when the operation succeeds.
Here is a complete example:
type Callback<T> = (error: Error | null, value?: T) => void;
function legacyLookup(key: string, callback: Callback<string>): void {
setTimeout(() => {
if (key.length === 0) {
callback(new Error("The key cannot be empty"));
return;
}
callback(null, `value for ${key}`);
}, 100);
}
function lookup(key: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
legacyLookup(key, (error, value) => {
if (error !== null) {
reject(error);
return;
}
if (value === undefined) {
reject(new Error("The callback returned no value"));
return;
}
resolve(value);
});
});
}
async function main(): Promise<void> {
try {
const value = await lookup("theme");
console.log(value);
} catch (error: unknown) {
if (error instanceof Error) {
console.error(error.message);
} else {
console.error("Unknown failure");
}
}
}
void main();The callback's value is optional because an error path may not provide one. Checking value === undefined narrows it to string before resolve(value) is called.
The wrapper translates callback events into promise events:
Important wrapper rules
Reject when the callback reports failure. Do not resolve with an error object, because that makes failures look like successful values.
Return after rejecting when the callback can continue executing. This prevents accidental use of an absent value.
The promise constructor also converts a synchronous throw from its executor into a rejection:
function risky(): Promise<string> {
return new Promise<string>((resolve) => {
throw new Error("Setup failed");
});
}Avoid making the executor async. An async executor can create an inner promise whose rejection the outer promise does not track correctly. Put await outside the constructor, or use a normal executor.
async function readValue(): Promise<string> {
return lookup("theme");
}A wrapper cannot repair every callback design. If an API can call its callback multiple times, the promise exposes only the first result. If the underlying operation needs cancellation or cleanup, the wrapper must connect that behavior explicitly, usually through an AbortSignal or a cleanup function.
Exercise
What should a wrapper do when an error-first callback receives a non-null error?
Show answer
It should call reject(error) and return without resolving the promise or using the missing success value.