What Is Promise Callback Function Async Await In In Javascript

What Is Promise Callback Function Async Await In In Javascript

5 min read Jun 18, 2024
What Is Promise Callback Function Async Await In In Javascript

Understanding Promises, Callback Functions, Async/Await in JavaScript

JavaScript, being a single-threaded language, often encounters situations where tasks take time to complete, such as fetching data from a server. This can block the execution of other code, leading to a non-responsive user interface. To overcome this, JavaScript utilizes asynchronous programming concepts, which allow for the execution of code even when other tasks are in progress. Let's explore the key concepts involved:

Callback Functions

A callback function is simply a function passed as an argument to another function. This function will be executed after the outer function has completed its task, often handling the result of that task.

function greet(name, callback) {
  console.log(`Hello, ${name}!`);
  callback(); 
}

function sayGoodbye() {
  console.log("Goodbye!");
}

greet("Alice", sayGoodbye);

In this example, sayGoodbye is a callback function passed to greet. It executes after greet finishes printing the greeting. This basic example demonstrates the core concept of callbacks.

Promises

Promises are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They are designed to handle the asynchronous nature of JavaScript in a more structured and readable way compared to traditional callback functions.

A Promise has three states:

  • Pending: The initial state, where the operation is still in progress.
  • Fulfilled: The operation completed successfully, and the result is available.
  • Rejected: The operation failed, and an error occurred.

Here's a simple example:

function fetchData(url) {
  return new Promise((resolve, reject) => {
    // Simulate fetching data from a server
    setTimeout(() => {
      const data = { name: "John", age: 30 }; 
      resolve(data); // Data fetched successfully
    }, 1000);
  });
}

fetchData('https://example.com/data')
  .then(data => console.log(data)) // Handle successful data
  .catch(error => console.error(error)); // Handle errors

In this example, fetchData returns a Promise. The then method is used to handle the fulfilled state and receive the resolved data, while the catch method is used to handle the rejected state and receive the error.

Async/Await

Async/await provides a cleaner and more readable way to work with promises. It makes asynchronous code look more like synchronous code.

  • async Keyword: An async function always returns a Promise.

  • await Keyword: Used within an async function, await pauses the function's execution until the Promise it is waiting for resolves.

async function fetchAndDisplay() {
  try {
    const data = await fetchData('https://example.com/data');
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

fetchAndDisplay(); 

This code, using async/await, achieves the same functionality as the previous example using .then and .catch. The await keyword waits for the Promise to resolve before proceeding, making the code more readable and less prone to callback nesting.

In Summary

Understanding Promises, Callback Functions, and Async/Await is crucial for writing efficient and readable asynchronous JavaScript code. They empower developers to handle asynchronous operations elegantly and enhance the overall user experience by preventing UI freezing during lengthy processes.