DEV Community

Pranav Bakare
Pranav Bakare

Posted on • Edited on

3 1

Asynchronous Programming in JavaScript - Callbacks | Promises | Async/Await

Image description

Understanding Asynchronous Programming in JavaScript -

JavaScript handles operations using synchronous and asynchronous approaches. The key to understanding asynchronous behavior is the event loop.

Synchronous and Asynchronous Code

Synchronous Code executes line by line, blocking subsequent lines until the current line finishes.

Example: Synchronous Code

console.log("First");
console.log("Second");

Enter fullscreen mode Exit fullscreen mode
Output:
First
Second

Enter fullscreen mode Exit fullscreen mode

Asynchronous Code allows some operations to run in the background and complete later, enabling other code to continue executing.

Example: Asynchronous Code with setTimeout()

console.log("First");

setTimeout(() => {
  console.log("Second");
}, 0);

console.log("Third");

Enter fullscreen mode Exit fullscreen mode
Output:
First
Third
Second
Enter fullscreen mode Exit fullscreen mode

Asynchronous Patterns in JavaScript

1. Callbacks

Callbacks are functions passed as arguments to other functions, executed after the first function completes.

Example: Callbacks

console.log("Start");

function asyncTask(callback) {
  setTimeout(() => {
    console.log("Async task completed");
    callback();
  }, 2000);
}

asyncTask(() => {
  console.log("Task finished");
});

console.log("End");

Enter fullscreen mode Exit fullscreen mode
Output:

Start
End
Async task completed
Task finished

Enter fullscreen mode Exit fullscreen mode

2. Promises

Promises represent a value that will be available in the future and can be used to handle asynchronous results.

Example: Promises

console.log("Start");

const asyncTask = new Promise((resolve) => {
  setTimeout(() => {
    console.log("Async task completed");
    resolve();
  }, 2000);
});

asyncTask.then(() => {
  console.log("Task finished");
});

console.log("End");

Enter fullscreen mode Exit fullscreen mode
Output:

Start
End
Async task completed
Task finished

Enter fullscreen mode Exit fullscreen mode

3. Async/Await

Async/await simplifies working with promises by allowing asynchronous code to be written in a more synchronous style.

Example: Async/Await

console.log("Start");

async function asyncTask() {
  await new Promise((resolve) => {
    setTimeout(() => {
      console.log("Async task completed");
      resolve();
    }, 2000);
  });

  console.log("Task finished");
}

asyncTask();

console.log("End");

Enter fullscreen mode Exit fullscreen mode
Output:

Start
End
Async task completed
Task finished
Enter fullscreen mode Exit fullscreen mode

This guide provides a foundation for understanding how JavaScript handles asynchronous operations and the event loop, helping you write efficient, non-blocking code.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay