Understanding Async/Await in JavaScript

Async/Await is a modern syntax in JavaScript that simplifies working with promises, making asynchronous code easier to read and write. It allows you to write asynchronous code that looks synchronous, improving readability and maintainability.


Async Functions

The async keyword is used to define an asynchronous function. When you prefix a function with async, it always returns a promise. If the function returns a value, JavaScript automatically wraps it in a resolved promise.


Example:

async function myFunction() {

return "Hello";

}

myFunction().then(alert); // "Hello"

This is equivalent to:


function myFunction() {

return Promise.resolve("Hello");

}


Await Keyword

The await keyword can only be used inside an async function. It makes JavaScript wait until the promise settles and returns its result. This allows you to write code that waits for asynchronous operations to complete without using .then().


Example:

async function myDisplay() {

let myPromise = new Promise((resolve) => {

resolve("I love You !!");

});

document.getElementById("demo").innerHTML = await myPromise;

}

myDisplay();


Error Handling

Error handling with async/await is straightforward. You can use try...catch blocks to handle errors just like in synchronous code.


Example:

async function fetchData() {

try {

let response = await fetch('http://no-such-url');

} catch (err) {

alert(err);

}

}

fetchData();

Using Async/Await with Promise.all


When you need to wait for multiple promises, you can use Promise.all with await. This allows you to run multiple asynchronous operations concurrently and wait for all of them to complete.


Example:

async function fetchMultipleUrls(urls) {

let results = await Promise.all(urls.map(url => fetch(url)));

return results;

}


Practical Example

Let's rewrite a promise-based function using async/await for better readability:


// Original promise-based function

function loadJson(url) {

return fetch(url)

.then(response => {

if (response.status == 200) {

return response.json();

} else {

throw new Error(response.status);

}

});

}

loadJson('https://javascript.info/no-such-user.json').catch(alert);


// Rewritten using async/await

async function loadJson(url) {

let response = await fetch(url);

if (response.status == 200) {

return await response.json();

} else {

throw new Error(response.status);

}

}

loadJson('https://javascript.info/no-such-user.json').catch(alert);


Summary

  • The async keyword before a function makes it return a promise and allows the use of await inside it.
  • The await keyword pauses the function execution until the promise settles and returns its result.
  • Error handling is done using try...catch blocks.
  • Promise.all can be used with await to handle multiple promises concurrently.


Async/await provides a powerful and elegant way to handle asynchronous operations in JavaScript, making the code more readable and easier to maintain.

Comments

Popular posts from this blog

Quotation marks to wrap an element in HTML

The Basic Structure of a Full-Stack Web App

Making GUI Calculator in Tkinter Python