JavaScript Async-Await

Level : Advanced
Mentor: Shailendra Chauhan
Duration : 00:01:30

Resolving JavaScript Promises:

Resolving promises involves handling asynchronous operations and obtaining their results.

Example:

let promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Resolved"), 1000);
});
promise.then(result => console.log(result)); // Output: Resolved

Creating async Function:

An async function is used to write asynchronous code in a more readable and structured way.

Example:

async function fetchData() {
  let response = await fetch('https://api.example.com/data');
  let data = await response.json();
  return data;
} 

Async Await Promises:

The async...await syntax simplifies working with promises, making asynchronous code look more like synchronous code.

Example:

async function getData() {
  try {
    let response = await fetch('https://api.example.com/data');
    let data = await response.json();
    return data;
  } catch (error) {
    console.error("Error:", error);
  }
} 

Using async await syntax:

The async...await syntax lets you pause the execution of an async function until a promise is resolved.

Example:

async function fetchData() {
  let response = await fetch('https://api.example.com/data');
  let data = await response.json();
  return data;
} 

JavaScript async…await advantage:

Async...await improves code readability by allowing sequential-style programming for asynchronous tasks.

Example:

async function processData() {
  let result1 = await fetch('https://api.example.com/data1');
  let result2 = await fetch('https://api.example.com/data2');
  return [result1, result2];
} 

Async Function Error Handling:

Async functions can use try...catch blocks for consistent error handling of asynchronous code.

Example:

async function fetchData() {
  try {
    let response = await fetch('https://api.example.com/data');
    let data = await response.json();
    return data;
  } catch (error) {
    console.error("Error:", error);
  }
} 

The async and await Keywords:

The "async" keyword is used to define a function that returns a promise. "await" is used within an async function to pause execution until the promise is resolved.

Example:

async function doSomething() {
  let result = await someAsyncFunction();
  return result;
} 
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this