DEV Community

VINOTH
VINOTH

Posted on

Synchronous vs Asynchronous vs Promise in JavaScript

In JavaScript, synchronous means code runs line-by-line in order, asynchronous means code can start a long-running task and move on immediately without waiting, and a Promise is a modern JavaScript object used to manage those asynchronous tasks cleanly.

Think of it like ordering food at a restaurant:

  • Synchronous: You stand in line, order, and wait at the register until your food is cooked. The line behind you is completely blocked.
  • Asynchronous: You order, get a buzzer, and sit down. You can check your phone while your food cooks.
  • Promise: The buzzer itself. It is a token that represents the future delivery of your meal.

1. Synchronous JavaScript (Sync):

  • JavaScript is synchronous and single-threaded.
  • It executes one command at a time in a strict sequence.
  • If a line of code takes 10 seconds to compute, the entire browser freezes and waits.

Characteristics: Sequential, predictable, blocking.

console.log("A");
console.log("B");
console.log("C");
Enter fullscreen mode Exit fullscreen mode

o/p:

A
B
C
Enter fullscreen mode Exit fullscreen mode

Flow:

A → finish
    ↓
B → finish
    ↓
C → finish
Enter fullscreen mode Exit fullscreen mode

2. Asynchronous JavaScript (Async):

  • Asynchronous programming allows JavaScript to offload long-running tasks (like fetching data from a server or waiting for a timer) to the browser background.
  • The main program keeps running without stalling.

Characteristics: Non-blocking, handles concurrent actions, relies on a callback queue.

console.log("A");

setTimeout(() => {
    console.log("B");
}, 2000);

console.log("C");
Enter fullscreen mode Exit fullscreen mode

o/p:

A
C
B
Enter fullscreen mode Exit fullscreen mode

Why?

A → executes immediately

setTimeout → waits for 2 seconds

C → executes immediately

After 2 seconds → B executes
Enter fullscreen mode Exit fullscreen mode

3. Promises (The Async Manager):

  • Historically, asynchronous tasks used basic callback functions. However, nesting multiple callbacks inside each other created unreadable code known as "Callback Hell".
  • A Promise is a placeholder for a value that you don't have yet but will receive in the future.

A Promise always exists in one of three states:

  • Pending: The background task is still working.
  • Fulfilled: The task completed successfully, and you get the result.
  • Rejected: The task failed, and you get an error message.

For example, imagine ordering food:

Order food
    ↓
Pending
    ↓
Food ready → Success
    OR
Problem → Failure
Enter fullscreen mode Exit fullscreen mode

A Promise has three states:

Pending
   ↓
   ├── Fulfilled ✅
   │
   └── Rejected ❌
Enter fullscreen mode Exit fullscreen mode

Example:

const promise = new Promise((resolve, reject) => {

    let success = true;

    if (success) {
        resolve("Success");
    } else {
        reject("Failed");
    }

});
Enter fullscreen mode Exit fullscreen mode

4. Handling a Promise:

We can use .then() and .catch().

promise
    .then((result) => {
        console.log(result);
    })
    .catch((error) => {
        console.log(error);
    });
Enter fullscreen mode Exit fullscreen mode
.then()

Used when the Promise is successful.

.catch()

Used when the Promise fails.
Enter fullscreen mode Exit fullscreen mode

5. Promise with fetch():

fetch() is commonly used to get data from an API.

fetch("https://fakestoreapi.com/products")
    .then((response) => response.json())
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.log(error);
    });
Enter fullscreen mode Exit fullscreen mode

Flow:

fetch()
   ↓
Promise
   ↓
Server Response
   ↓
response.json()
   ↓
Data
Enter fullscreen mode Exit fullscreen mode

Easy way to remember:

Synchronous
→ WAIT → NEXT

Asynchronous
→ DON'T WAIT → NEXT

Promise
→ RESULT WILL COME LATER

async/await
→ EASY WAY TO HANDLE PROMISE
Enter fullscreen mode Exit fullscreen mode

Top comments (0)