DEV Community

Sajin Joe J
Sajin Joe J

Posted on

Synchronous, Asynchronous, and Promise in Javascript

1. Synchronous JavaScript
Synchronous means code executes one line at a time, in order. The next line waits until the current line finishes.
Example:

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

Output :

First
Second
Third
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • First line executes.
  • Then the second line executes.
  • Finally, the third line executes. Each statement runs in sequence.

2. Asynchronous JavaScript
Asynchronous means some operations can start and finish later, allowing other code to run while waiting.

console.log("First");

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

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

Output :

First
Third
Second
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • "First" prints immediately.
  • setTimeout() schedules the callback to run after at least 2 seconds.
  • "Third" prints without waiting for the timer.
  • "Second" prints when the timer callback run

3. 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: The operation has not finished.
  • Fulfilled: The operation succeeded.
  • Rejected: The operation 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!
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • new Promise() creates a Promise.
  • resolve() indicates success.
  • .then() handles the successful result.
  • reject() is used to indicate failure.

Here's an example of a rejected Promise:

let myPromise = new Promise((resolve, reject) => {
    reject("Something went wrong");
});

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

Output :

Something went wrong
Enter fullscreen mode Exit fullscreen mode

Top comments (0)