Exploring concepts of Asynchronous JavaScript, Web APIs, and Promises.

·

5 min read

Asynchronous JavaScript

In JavaScript, sometimes we have tasks that take time, like fetching data or waiting for a user to do something. Asynchronous code allows us to keep our program running smoothly, doing other things, instead of waiting for each task to finish before moving on.

This is super important in web development because websites must do many things simultaneously, like loading data, responding to user clicks, or showing animations. Asynchronous JavaScript helps us manage these tasks efficiently without slowing down the entire program.

what are ways we can make a code into Async?

1. Callbacks:

A callback function in JavaScript is a function that is passed as an argument to another function and is executed later, often after the completion of an asynchronous operation or some other event.

//created function called student and given a callBack function as parameter
function student(callBack) { 
//setting time for execution using setTimeOut()
  setTimeout(() => {
    const studentName = "Ravi";
    callBack(studentName);
  }, 3000);
}
//calling student function and implementing callBack function
student((result) => {
  console.log(result);
});

2. Promises:

A Promise in JavaScript is an object representing an asynchronous operation's eventual completion or failure. It is a way to work with asynchronous code in a more structured and manageable manner. Promises provide a cleaner alternative to using callbacks to handle asynchronous operations results.

//created a function called order
function order() {
//created a promise which has resolve and reject as parameter and returning the promise
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const oderId = "1234";
      resolve(oderId); //resolving the promise
    }, 3000);
  });
}

order()
  .then((result) => {
    console.log(result);
  })
//if promise is not resolved catch will be executed
  .catch((error) => {
    console.log(error);
  });

3. Async/Await:

Async/Await is a feature in modern JavaScript that simplifies and enhances the readability of asynchronous code. It is built on top of Promises and provides a more straightforward and synchronous-like syntax for dealing with asynchronous operations.

The async keyword is used to define a function that returns a Promise, and await is used to pause execution until the Promise is settled.

//created a function and decleared it as async
async function student() {
//created promise and returning it
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const studentId = "1234";
      resolve(studentId);
    }, 3000);
  });
}
//created a function and decleared it as async
async function getStudentId() {
  try {
    const studentId = await student(); //using await and calling student(
    console.log(studentId);
  } catch (error) {
    console.log(error);
  }
}
getStudentId(); //calling function

Role of Web APIs in Asynchronous JavaScript

Web APIs play a crucial role in introducing asynchronous behavior to JavaScript by offering essential functionalities. These include the ability to initiate HTTP requests, control timers, and interact with the Document Object Model (DOM). Notable examples of these APIs encompass the fetch API, designed for handling network requests, and the setTimeout function, which allows the introduction of delays in the execution of code. Understanding and utilizing these APIs are key elements in creating dynamic and responsive JavaScript applications.

HTTP Requests with Fetch API:

  • The fetch API is a modern and standard way to make asynchronous HTTP requests in JavaScript. It returns a Promise, allowing developers to handle the results using then and catch. The Fetch API simplifies the process of fetching data from servers and interacting with web services.
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Managing Timers with set timeout:

  • The set timeout function is part of the browser's Web APIs, and it allows you to introduce delays in code execution. It's commonly used for scheduling tasks to be executed after a specified amount of time, providing a way to handle asynchronous behavior.
setTimeout(() => {
  console.log('This code runs after a delay');
}, 1000); // Run after 1000 milliseconds (1 second)

Promises and their function

Creation of Promises:

  • The promise constructor is used to create a new Promise object. It takes a function as an argument, commonly referred to as the "executor" function. The executor function has two parameters: resolve and reject. These are functions provided by the Promise implementation.
const myPromise = new Promise((resolve, reject) => {
  // If successful, call resolve with the result
  // If there's an error, call reject with the reason
});

States of a Promise:

  • Promises have three states:

    • Pending: The initial state when the Promise is created, and the asynchronous operation is ongoing.

    • Fulfilled: The state when the asynchronous operation is successful. The result is available, and the resolve function is called.

    • Rejected: The state when the asynchronous operation encounters an error. The reason for the error is provided through the reject function.

Handling Promises:

  • Promises can be handled using the .then() and .catch() methods. The .then() method is used to handle the fulfillment of a Promise, and the .catch() method is used to handle rejections.
myPromise
  .then(result => {
    // Handle successful result
  })
  .catch(error => {
    // Handle error
  });

Chaining Promises:

  • Promises can be chained using the .then() method. This is useful for sequential execution of asynchronous operations.
myPromise
  .then(result => {
    // Do something with the result
    return anotherPromise;
  })
  .then(anotherResult => {
    // Handle the result of anotherPromise
  })
  .catch(error => {
    // Handle any error in the chain
  });