Sub topic 1
Promise<T>: the type of a value that arrives later
Prerequisites
Assume you know basic TypeScript types, functions, generics, union narrowing, and JavaScript promises with async and await.
Promise<T>: the type of a value that arrives later
A Promise<T> represents an operation that will eventually produce a value of type T. It can also fail by rejecting. For example, Promise<string> means “a promise whose successful result is a string.”
A promise has three runtime states:
- Pending: the operation has not finished.
- Fulfilled: the operation produced a value.
- Rejected: the operation failed.
The type parameter describes only the fulfilled value. It does not describe the rejection type, because JavaScript allows code to throw any value.
Async functions always return a Promise
An async function always returns a promise, even when its source code returns an ordinary value. The declared return type should therefore be Promise<T>.
async function fetchLength(url: string): Promise<number> {
const res = await fetch(url);
const text = await res.text();
return text.length;
}The return statement supplies a number, and TypeScript wraps that result in Promise<number>. Calling fetchLength gives you a promise, so the caller must use await or handle the promise with methods such as .then() and .catch().
Creating promises and wrapping callback APIs
Use the Promise constructor when an API reports completion through callbacks. The executor receives resolve for success and reject for failure.
function delay(ms: number): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(resolve, ms);
});
}
async function main(): Promise<void> {
await delay(100);
console.log("Finished");
}
void main().catch(console.error);Promise<void> means successful completion has no value. Always connect rejection handling when starting an asynchronous operation that you do not await.
Exercise
What is the return type of an async function that returns a boolean?
Show answer
Promise<boolean>.