Promises
| Pending fulfilled rejected | |
| Construct one | |
| Then returns | |
| Catch at the end |
Pending fulfilled rejected
Every promise is pending, fulfilled, or rejected. Pending means the work is still running. Fulfilled means a value is ready, while rejected means an error stopped the work. See also promises in JavaScript for the same states in plain script.
const fast: Promise<string> = Promise.resolve("ok");
const bad: Promise<string> = Promise.reject(new Error("no"));
bad.catch(() => {
console.log("caught");
});
Construct one
Use the Promise constructor to wrap timer or callback logic. Call resolve with the value or reject with the error. The executor runs right away when the object is created.
function wait(ms: number): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
resolve("done");
}, ms);
});
}
Then returns
Then always returns a fresh promise, so calls can chain. Return a value to fulfill the next link. Return another promise to pause the chain until that inner work ends.
wait(50)
.then((msg) => msg.length)
.then((len) => {
console.log(len);
});
Catch at the end
Put one catch at the end of the chain to collect errors from any step. The handler gets the rejection reason as unknown. Log it, recover with a default, or rethrow to keep failing loudly.
wait(50)
.then(() => {
throw new Error("late boom");
})
.catch((err: unknown) => {
console.log(err);
});
Next: async and await
Article author: Arthur Isaev