0
0
JavascriptConceptBeginner · 3 min read

What is Promise in JavaScript: Simple Explanation and Example

A Promise in JavaScript is an object that represents the eventual completion or failure of an asynchronous operation. It allows you to write code that waits for a task to finish and then handles the result or error in a clean way.
⚙️

How It Works

Think of a Promise like a ticket you get when you order a package online. The package might arrive now, later, or maybe not at all. The ticket (the promise) tells you that the package will come in the future. You can check the ticket to see if the package has arrived (fulfilled), if it was lost (rejected), or if it is still on the way (pending).

In JavaScript, a Promise starts in a pending state. When the task finishes successfully, it moves to fulfilled and gives you the result. If something goes wrong, it moves to rejected and gives you the error. You can attach functions to run when the promise is fulfilled or rejected, so your code knows what to do next.

💻

Example

This example shows a promise that waits 2 seconds and then says "Task completed!". It uses then to handle success and catch to handle errors.

javascript
const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    const success = true;
    if (success) {
      resolve('Task completed!');
    } else {
      reject('Task failed.');
    }
  }, 2000);
});

myPromise
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.error(error);
  });
Output
Task completed!
🎯

When to Use

Use Promises when you have tasks that take time to finish, like loading data from the internet, reading files, or waiting for user actions. Promises help keep your code clean and easy to read by avoiding deeply nested callbacks.

For example, when fetching data from a website, a promise lets you wait for the data to arrive before using it. If the fetch fails, you can handle the error gracefully without crashing your program.

Key Points

  • A Promise represents a future result of an asynchronous task.
  • It has three states: pending, fulfilled, and rejected.
  • You use then to handle success and catch to handle errors.
  • Promises make asynchronous code easier to write and understand.

Key Takeaways

A Promise handles asynchronous tasks by representing future results.
Promises have three states: pending, fulfilled, and rejected.
Use then() to process success and catch() to handle errors.
Promises help avoid messy nested callbacks in your code.