Async Stuff
Promise
Promises are a useful tool for working with asynchronous code in JavaScript because they provide a way to handle the results of asynchronous operations consistently and predictably. However, promises can be somewhat complex to work with, because they require you to use callback functions and manage the state of the promise.
The
async
and await
keywords in TypeScript provide a way to simplify working with promises by allowing you to write asynchronous code that looks and behaves like synchronous code. When you use async
and await
, you can use the await
keyword to wait for the result of a promise, and the code that follows the await
keyword will be executed only when the promise is resolved. This makes it easier to write asynchronous code that is easy to read and understand.However, it is important to note that
async
and await
are just syntax sugar on top of promises. They are not a completely different way of writing asynchronous code, but rather a way to make promises easier to work with. Behind the scenes, async
and await
still use promises to manage the flow of asynchronous operations.Typing promises
You can use the built-in
Promise
type to specify the type of a promise. The Promise
type is a generic type that takes two type arguments: the type of the resolved value of the promise, and the type of the rejected value of the promise.For example, if you have a promise that resolves to a
string
and rejects with an Error
object, you could specify the type of the promise like this:let promise: Promise<string, Error>;
In this code, the
Promise<string, Error>
type specifies that the promise
variable is a promise that resolves to a string
and rejects with an Error
object.You can also use the
Promise
type to specify the type of a function that returns a promise. For example, if you have a function that returns a promise that resolves to a string
and rejects with an Error
object, you could specify the type of the function like this:function someAsyncFunction(): Promise<string, Error> {
// asynchronous code goes here
}
In this code, the
Promise<string, Error>
type specifies that the someAsyncFunction()
function returns a promise that resolves to a string
and rejects it with an Error
object.The
Promise
type in TypeScript is a useful tool for specifying the type of a promise, and it allows you to specify the type of the resolved and rejected values of the promise. This can help to ensure that your code is correct and free of type errors.