Evolution of Asynchronous Function in JavaScript

Evolution of Asynchronous Function in JavaScript

Introduction:

The evolution of asynchronous programming in JavaScript has been a transformative journey.From traditional callback patterns to the advent of Promises and, ultimately, the elegant solution brought by async functions, JavaScript has come a long way in providing more readable and maintainable code for handling asynchronous tasks.

In this article, we'll delve into the evolution of asynchronous programming in JavaScript, exploring the challenges posed by callback hell, the introduction of Promises for improved control flow, and how async functions have emerged as a syntactic sugar.

Callback Function/Hell:

In JavaScript, a callback is a function that is passed as an argument to another function. They are essential for handling asynchronous operations, such as fetching data or responding to user events, enabling non-blocking execution.

const performTask = (task, callback) => 
{
  console.log(`Task started: ${task}`);
  setTimeout(() => 
{
    console.log(`Task completed: ${task}`);
    callback();
  }, 1000);
};

// Usage
performTask("Fetch Data", () => 
{
  performTask("Process Data", () => 
{
    performTask("Display Result", () => 
{
      console.log("All tasks completed!");
    });
  });
});        

In Older days people were using a callback, but it is very complex to read for anytime and for other developers.Then they avoid callback they would use thenables making them compatible with promises and the Promise API.

What is Js Promises?

Promises in JavaScript provide an organized way to handle asynchronous operations. Think of a promise as a placeholder for the eventual result of an asynchronous task.

Promises help avoid callback hell by allowing chaining of asynchronous tasks, enhancing code readability. They are integral to modern JavaScript development, forming the basis for async/await, a syntax further simplifying asynchronous code for a more synchronous-like experience.

How to Use Promises to Escape Callback Hell:

Promises were introduced in JavaScript to address the issue of callback hell (or callback pyramid) and to provide a more structured and readable way to handle asynchronous operations.

const myPromise=new Promise((resolve,reject)=>{
    const error=false;
    if(!error)
    {
        resolve("Yes!,resolved the promise")
    }
    else
    {
        reject("No rejected the promise")
    }
})


const myNextPromise=new Promise((resolve,reject)=>{
    setTimeout(function()
    {
        resolve("myNextPromise resolved")
    },3000 )
})

myNextPromise.then(value=>
{
    console.log(value)
})
myPromise
.then(value=>
{
    console.log(value)
})        

Promises have three stages:

  1. Pending - If it take time to fetch data from api or server it will set pending stage.
  2. Fullfilled - If function successfully fetch data from api/server it will set fullfiled stage.
  3. Rejected - While fetching the data, due to some error it can be failed.then it can set to rejected stage.

How Does Async / Await Work in JavaScript?

The async/await syntax provides a more concise and readable approach to working with promises, contributing to cleaner and simpler code. By simply adding the keyword async before a regular function, it transforms into a promise, streamlining the handling of asynchronous operations.

Async / Await can improve the readablity of the code.

const myUsers={
    userList:[]
}

// Async/Await
const users= async ()=>
{
    const response= await fetch("https://jsonplaceholder.typicode.com/comments")
    const userData= await response.json()
    anotherFunction(userData)
   
   return userData
}

const anotherFunction=(data)=>
{
   
    myUsers.userList=data
    console.log(myUsers)
    return data
}
users();
console.log(myUsers)        

Let's look at a Async / Await difference:

  1. Async Keyword:The async keyword is used to define asynchronous functions in JavaScript.Functions marked as async always return a promise, whether implicitly or explicitly.
  2. Await Keyword:The await operator is used inside async functions to pause execution until the promise is settled (resolved or rejected).It can only be used within async functions.
  3. The await operator can be used only if declared a function with async keyword, so be concise with that functionality.

Now let's look up to when to use async and await :)-

When the async keyword is used before a function declaration, it means the function will always return a Promise.

async function fetchData() {
  return "Data fetched!";
}

// Usage
fetchData().then(response => console.log(response));        

The await operator is used inside an async function to pause the execution until the Promise is settled (fulfilled or rejected). It makes asynchronous code look and behave more like synchronous code.

async function fetchData() {
  const data = await     fetch('https://jsonplaceholder.typicode.com/comments"');
  console.log(data);
}

// Usage
fetchData();        

Conclusion:

The evolution of JavaScript's asynchronous programming has seen significant advancements with the introduction of promises and the subsequent simplification brought by the async/await syntax.Embracing the modern approach of async/await enhances code simplicity, making it an integral part of contemporary JavaScript development.


kesavan Ranganathan

Attended Coimbatore Institute of Technology

6 个月

Helpful! This will

回复
kesavan Ranganathan

Attended Coimbatore Institute of Technology

7 个月

Keep going bro Nisanth Selvaraj

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了