Content is user-generated and unverified.

Understanding Async/Await in JavaScript

Async Keyword

  • Async is a keyword used to define a function which runs asynchronously
  • It always returns a promise
  • Even if it returns a value, that value will be automatically wrapped in a promise

Basic Promise Example

javascript
const p = new Promise((resolve, reject) => {
    resolve("resolved");
});

function handle() {
   p.then((ms) => console.log(ms));
}

Promise Timing Examples

javascript
const p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("hi swathi");
    }, 20000)
});

const p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("hi swathi");
    }, 40000)
});

Async Without Await

javascript
async function handle() { // returns promise only
   p1.then((ms) => console.log(ms)); // then this
   console.log("how are you swathi", p1); // this will be printed first as JS does not wait for anything
   
   // But what if in real world scenario if the promise result is needed in further transaction
   // or if previous transaction result is needed in next? Then it doesn't work right,
   // so await came into picture
}

Async With Await

javascript
async function handle1() { // returns promise only
    console.log(":helloo");
    
    const data = await p1; // 10sec
    // Call stack: First whenever handle1 enters into call stack it starts executing line by line
    // so first prints hello and when it encounters await, then the function execution will be suspended
    // from call stack but JS doesn't stop its execution while callstack is ready to execute other events
    // which ever comes into it without blocking main thread
    
    // Once the promise is settled then it goes ahead into call stack and starts executing from where it was called
    // If it encounters await in our code and if it is already settled then simply returns it
    // Otherwise again the function execution will be suspended and it will wait until promise to be settled
    // then it appears in call stack to resume execution from where it was called.
    
    console.log(data); // after promise settled this line will be executed
    console.log("how are you"); 
    
    const data1 = await p2; // 5sec
    console.log(data1); // after promise settled this line will be executed
    console.log("how are you2");
}

Real Example with API

javascript
const API_URL = "https://api.github.com/user"; // fetch is browser API, not JS one

async function handler2() {
  const data = await fetch(API_URL); // it will return the response stream
  // from that response stream we need to get response JSON, it's again a promise
  const res = await data.json();
  console.log(res);
}

// handler2();

Error Handling in Async/Await

javascript
// To handle errors we use try-catch in our async and await 
// whereas in promise it's then and catch

// Method 1: Try-catch inside function
async function handler2() {
    try {
        const data = await fetch(API_URL);
        const res = await data.json();
        console.log(res);
    } catch(err) { 
        console.log(err);
    }
}

// Method 2: Attaching catch to function call
handler2().catch((err) => console.log(err)); // here we need to attach failure callback to it
Content is user-generated and unverified.
    Organized Async/Await Notes | Claude