Learn Callbacks / Promises / Async-await

Learn Callbacks / Promises / Async-await

learn what matters

In JavaScript, asynchronous methods are crucial for executing tasks without blocking the main execution thread. Here are some common asynchronous methods and techniques used in JavaScript:

  1. Callbacks: Traditional way of handling asynchronous code execution by passing a function to be executed once the asynchronous operation completes.

  2. Promises: Introduced in ES6, promises provide a cleaner way to deal with asynchronous code by representing a value that might be available now, or in the future, or never.

  3. Async/Await: Also introduced in ES8, async/await provides a more readable and synchronous-looking syntax for writing asynchronous code using promises.

  4. setTimeout(): Executes a function after a specified delay.

  5. setInterval(): Executes a function repeatedly at specified intervals.

  6. XMLHttpRequest (XHR): The classic way of making asynchronous HTTP requests in JavaScript, although nowadays, it's often replaced by the more modern Fetch API.

  7. Fetch API: A modern replacement for XMLHttpRequest, providing a more powerful and flexible way to make HTTP requests.

  8. Event Listeners: Functions that are executed in response to certain events, allowing for asynchronous behavior in response to user actions or other events.

  9. FileReader API: Used for reading the contents of files asynchronously.

  10. Web Workers: Enables running JavaScript code in background threads, allowing for parallel execution without blocking the main UI thread.

Callbacks:

call backs function hmesha async code mein answer/response aane ke bad chalte hai

 setTimeout(callback,3000);

/* yha callback ek function hai jo ki async code likhte hai vha use me ata
 hai ye jb data end server se aa jay toh y call+back ho jata hai. ye khud 
call hoker data ko de deta hai */

//data lene k liye .then

// or error k liye catch then k andr -->>> .then(callback) .catch(callback);

Promise

Promise: After callback hell problem promise introduced into in JS, okay.

Promises were introduced in JavaScript in ECMAScript-6 (ES6).

then role of promises in js : promises are a mechanism for handling asynchronous operations

how to use promise: You create a promise using the Promise constructor. This constructor takes a function as an argument, okay.

The new Promise() syntax is a way to create a new Promise instance. Yeh ek built-in constructor function hai, jise JavaScript provide karta hai.

new keyword ka istemal JavaScript mein ek naya object banane ke liye hota hai.new Promise() ka istemal karte hain, toh ek naya Promise object banaya jata hai,jise aap phir se use kar sakte hain.

Har ek Promise object apne khud ke asynchronous operation ko represent karta hai, aur then() aur catch() methods ke through aap uske outcome ko handle kar sakte hain.

Is tarah se, new keyword ek naya unique space provide karta hai har ek Promise ke liye, jisse har ek Promise ka apna alag context hota hai aur ve dusre Promises se separate rehte hain.

Okay so i understand new keyword, now back to promises.

So promise function take two parameters which is actually are functions

  1. resolve: Yeh ek function hai jo promise ko successfully complete hone par call kiya jata hai. Jab aap kisi asynchronous task ko successfully complete karte hain, toh aap resolve function ko call karte hain, aur iske andar result ko pass karte hain.

  2. reject: Yeh bhi ek function hai jo promise ko fail hone par call kiya jata hai. Agar kisi bhi wajah se asynchronous task mein koi error aata hai ya task fail ho jata hai, toh aap reject function ko call karte hain, aur iske andar error object ko pass karte hain.

     const myPromise = new Promise((resolve, reject) => {
       // Asynchronous operation
       setTimeout(() => {
         const success = true;
         if (success) {
           resolve('Operation completed successfully');
         } else {
           reject(new Error('Operation failed'));
         }
       }, 2000);
     });
    

Jab aap resolve ya reject function ko call karte hain, aapko sirf ek hi parameter dena hota hai, jo aapke asynchronous operation ka result hai. Aap apne requirement ke hisab se is parameter mein koi bhi data pass kar sakte hain, jo aap chahein, jaise ki ek string, number, object, array, ya koi aur data type ho sakta hai.

Now, Lets Talk About .then() & catch(), we read on starting of article that

then k andr -->>>   .then(callback)
                     .catch(callback);

use kya hai .thenka: jb resolve ho jaye mtlb data aa jay server se toh next kya krna hai vo .then k andr likna hai

.then k para me ek call+back function likhte hai uske para me hm data ko pass krta hai or us data k sath kya perform krna hai vo likh

Ji haan, bilkul sahi samajh rahe hain. Jab aap resolve function ko call karte hain, aap apne asynchronous operation ka result ko promise ke saath return karte hain. Uske baad, aap .then() method ka istemal karke promise ke result ko access kar sakte hain aur uske saath kuch actions perform kar sakte hain.

Jab aap .then() method ka istemal karte hain, aapko ek callback function provide karna hota hai, jo promise ke resolve hote hi execute hota hai aur promise ke result ko parameter ke roop mein le leta hai.

Yahan ek udaharan hai:

const myPromise = new Promise((resolve, reject) => {
  // Simulating data fetch from server
  setTimeout(() => {
    const data = { message: 'Data received from server', status: 'success' };
    resolve(data);
  }, 2000);
});

// Accessing promise result using .then() method
myPromise.then((result) => {
  console.log(result); // Output: { message: 'Data received from server', status: 'success' }
  // Perform actions with the result here
}).catch((error) => {
  console.error(error);
});

Is udaharan mein, .then() method ka istemal kiya gaya hai promise ke result ko access karne ke liye. Jab promise resolve hota hai, .then() method ke andar di gayi callback function execute hoti hai, aur promise ka result (yani data) callback function ke parameter ke roop mein milta hai. Aap us result ke saath kuch actions perform kar sakte hain, jaise use console mein log karna ya kuch aur processing karna.

Async & await

why to use async & await

One of the main problems with promises is that they can lead to "callback hell" or "pyramid of doom" when dealing with multiple asynchronous operations. This occurs when you have several nested .then() calls, making the code difficult to read and maintain. Additionally, error handling in promises can sometimes be cumbersome, especially when dealing with multiple promises.

Here's an example of how callback hell might look with promises:

Here's how the same code might look using async/await:

fetch('url1')
  .then(response => {
    return response.json();
  })
  .then(data1 => {
    fetch('url2')
      .then(response => {
        return response.json();
      })
      .then(data2 => {
        fetch('url3')
          .then(response => {
            return response.json();
          })
          .then(data3 => {
            // Do something with data1, data2, and data3
          })
          .catch(error => {
            console.error('Error fetching data from url3:', error);
          });
      })
      .catch(error => {
        console.error('Error fetching data from url2:', error);
      });
  })
  .catch(error => {
    console.error('Error fetching data from url1:', error);
  });

To address these issues, async/await was introduced in JavaScript. async/await is a syntactic sugar built on top of promises, making asynchronous code look and behave more like synchronous code. It allows you to write asynchronous code in a more sequential and readable manner, without the need for nested .then() calls.

async function fetchData() {
  try {
    const response1 = await fetch('url1');
    const data1 = await response1.json();

    const response2 = await fetch('url2');
    const data2 = await response2.json();

    const response3 = await fetch('url3');
    const data3 = await response3.json();

    // Do something with data1, data2, and data3
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

fetchData();

As you can see, the async/await syntax results in cleaner and more readable code, with error handling centralized in a single try/catch block. This makes it easier to understand and maintain asynchronous code, especially when dealing with multiple asynchronous operations.

did you know Async function return a promise

      // Async function
      async function myAsyncFunction() {
        return "Hello, world!";
      }

      // Call the async function
      const result = myAsyncFunction();

      console.log(result);   

//output in console:  Promise()