DEV Community

Cover image for JavaScript Promises for Beginners 🚀
Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

JavaScript Promises for Beginners 🚀

When I started learning JavaScript, I learned about variables, functions, arrays, and DOM manipulation. Then I came across Promises.

At first, Promises looked confusing, but simple examples helped me understand them.

What is a Promise?

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

For example, imagine ordering food online 🍕. Your order may be accepted, rejected, or still processing.

Promises have three states:

Pending – The operation is still in progress.

Fulfilled – The operation completed successfully.

Rejected – The operation failed.

Creating a Promise

Let's create a simple Promise.

let myPromise = new Promise((resolve, reject) => {
  let success = true;

  if (success) {
    resolve("Task completed!");
  } else {
    reject("Task failed!");
  }
});
Enter fullscreen mode Exit fullscreen mode

Here:

resolve() indicates success.

reject() indicates failure.

Using .then() and .catch()

We can handle the result of a Promise using .then() and .catch().

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

Output:

Task completed!

.then() handles successful completion.

.catch() handles errors.

Promise with setTimeout()

Let's simulate a task that takes two seconds.

let task = new Promise((resolve) => {
  setTimeout(() => {
    resolve("Data loaded successfully!");
  }, 2000);
});

task.then(result => console.log(result));
Enter fullscreen mode Exit fullscreen mode

The message appears after two seconds.

Using Promises with the DOM

Now let's display the result on a webpage.

<h2 id="message">Loading...</h2>

let message = document.getElementById("message");

function loadData() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("Welcome to JavaScript!");
    }, 2000);
  });
}

loadData().then(result => {
  message.textContent = result;
});
Enter fullscreen mode Exit fullscreen mode

Here, the DOM displays Loading... first and updates the text after two seconds.

This demonstrates how Promises and DOM manipulation can work together.

Why Are Promises Useful?

Promises are commonly used for:

Fetching data from APIs

Loading information from a server

Handling asynchronous operations

Managing success and error responses

Conclusion

Promises help us handle operations that don't finish immediately. Understanding resolve(), reject(), .then(), and .catch() is a great first step toward learning asynchronous JavaScript.

Learn → Practice → Build → Improve! 🚀

javascript #promises #webdev #beginners

Top comments (0)