Today we’ll learn one of the most essential things in JavaScript, “How to use Async Await”.
If you have just started learning to use Asynchronous Javascript I recommend you read “What are Asynchronous Functions?” first.
When writing JavaScript, you’ll eventually need to do some processes that might take a few seconds to complete. JavaScript can’t really multitask since it’s a single-threaded language, so we’ll need a way to handle those asynchronous processes.
Async Await
To use it, you can declare a function with the async
keyword before the function definition. Within that function, you can use the await
keyword before a promise to pause the execution of the function until the promise is resolved. Here’s an example:
async function fetchData() {
const response = await fetch('https://api.example.com');
const data = await response.json();
console.log(data);
}
fetchData();
In this example, the function “fetchData” is declared as async. Inside the function, the “await” keyword is used to wait for the fetch call to complete, and for the resulting promise to resolve. Once that promise is resolved, the function continues executing and “response.json()” is called and awaited.
It’s important to note that when using async/await, you should always wrap the code that uses it in a try/catch block, in case an exception is thrown while the promise is resolving.
async function fetchData() {
try {
const response = await fetch('https://api.example.com');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
Also, if you need to run multiple async functions parallelly, you can use Promise.all() function and pass an array of async functions inside it.
const [res1, res2] = await Promise.all([
fetch('https://api.example.com/1'),
fetch('https://api.example.com/2')
]);
Promise/Resolve
A promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises provide a way to register callbacks to be called when the promise is fulfilled (resolved) or rejected.
The resolve
function is used to fulfill a promise and it is passed as the first argument to the executor function when creating a new promise.
Here is an example:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Hello World!');
}, 1000);
});
promise.then(console.log);
// logs "Hello World!" after one second
In this example, we are creating a new promise and passing an executor function to it. Inside the executor function, we are using setTimeout
function to wait for one second, and then calling resolve
function with the value “Hello World!”. We are also registering a then
callback on the promise, which will be called with the resolved value when the promise is fulfilled.
You can also pass a value directly to resolve function
const promise = new Promise(resolve => resolve('Hello World!'));
promise.then(console.log); // logs "Hello World!"
It’s important to note that the resolve
function can only be called once, and any subsequent calls will be ignored. Also, once a promise is resolved or rejected, it can’t be changed.
You can use Promise.resolve()
and Promise.reject()
to create a resolved or rejected promise, respectively.
const resolvedPromise = Promise.resolve('Hello World!');
resolvedPromise.then(console.log); // logs "Hello World!"
const rejectedPromise = Promise.reject(new Error('Something went wrong'));
rejectedPromise.catch(console.error); // logs the error message
It’s also important to note that Promise.resolve(promise)
returns the same promise that you passed to it.
const originalPromise = new Promise(resolve => resolve('Hello World!'));
const newPromise = Promise.resolve(originalPromise);
console.log(originalPromise === newPromise); // true
I hope you found this useful, feel free to leave a comment since it could help other people better understand async JavaScript.
Also if you are getting started in your journey of learning programming read my article “The Best Way to Learn Programming“.