DEV Community

Cover image for Synchronous vs Asynchronous vs Promise in JavaScript 🚀
Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

Synchronous vs Asynchronous vs Promise in JavaScript 🚀

  1. What is Synchronous JavaScript?

Synchronous means one task executes at a time, in order. The next task waits until the current task finishes.

console.log("First");
console.log("Second");
console.log("Third");
Enter fullscreen mode Exit fullscreen mode

Output:

First
Second
Third

Each statement executes in order.

Real-life example: Standing in a queue. One person finishes before the next person is served.

  1. What is Asynchronous JavaScript?

Asynchronous operations allow JavaScript to continue doing other work while waiting for certain tasks to finish.

console.log("First");

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

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

Output:

First
Third
Second

Why? setTimeout() schedules the callback to run later, so JavaScript continues with the next statement first.

  1. What is a Promise?

A Promise is a JavaScript object that represents the eventual success or failure of an asynchronous operation.

A Promise has three states:

Pending – Still waiting.

Fulfilled – Completed successfully.

Rejected – Failed.

Example:

let myPromise = new Promise((resolve, reject) => {
  resolve("Task completed!");
});

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

Output:

Task completed!

Top comments (0)