Typescript: Promise & Async
In TypeScript, async
and Promise
are two separate concepts, but they are often used together to perform asynchronous operations.
A Promise
is an object that represents the eventual completion (or failure) of an asynchronous operation and allows you to handle the result of that operation. Promises are used to handle the return value of asynchronous functions and provide a way to chain multiple asynchronous operations together.
On the other hand, async
is a keyword that is used to define a function as asynchronous. An async
function always returns a Promise
, and it allows you to use await
inside the function to wait for the resolution of another Promise
before continuing the execution.
Here is an example of how to use async
and Promise
together in TypeScript:
async function fetchUser(userId: number): Promise<User> {
const response = await fetch(`/users/${userId}`);
const data = await response.json();
return new User(data);
}
fetchUser(123)
.then(user => console.log(user))
.catch(error => console.error(error));
In this example, the fetchUser
function is defined as async
, which means it returns a Promise
. Inside the function, it uses await
to wait for the response from the server before parsing the JSON data and returning a new User
object. The returned Promise
can be handled with the then
and catch
methods, which will be called when the Promise
is resolved or rejected, respectively.
Promise
Here’s a TypeScript promise example:
function getData(): Promise<string> {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data has been fetched successfully!');
}, 2000);
});
}
getData().then((result) => {
console.log(result);
}).catch((error) => {
console.error(error);
});
In this example, we have a function getData()
that returns a promise that resolves to a string after 2 seconds. We call this function and then use .then()
to handle the resolved value and .catch()
to handle any errors that might occur.
Async
Sure, here’s an example of using async/await in TypeScript to fetch data from an API:
async function fetchUsers() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
fetchUsers();
In this example, fetchUsers()
is an async function that uses the await
keyword to wait for the response from the API before proceeding with the next line of code. The try/catch
block is used to handle any errors that might occur during the fetch request. The API used here is the JSONPlaceholder API, which returns a list of users in JSON format. The data
variable holds the parsed response data, which is then logged to the console.