SyntaxStudy
Sign Up
JavaScript Intermediate 8 min read

Introduction to Promises

Introduction to Promises

A Promise is an object that represents the eventual completion or failure of an asynchronous operation. Introduced in ES2015, promises provide a cleaner, more composable alternative to callback-based async code.

Promise States

A promise exists in one of three states: pending (initial, neither fulfilled nor rejected), fulfilled (operation completed successfully), or rejected (operation failed). Once settled (fulfilled or rejected) a promise cannot change state.

then, catch, finally

Chain .then(onFulfilled) to handle success, .catch(onRejected) to handle errors, and .finally(fn) to run cleanup code regardless of outcome. Each .then() returns a new promise, enabling method chaining.

Creating Promises

Use the Promise constructor with an executor function that receives resolve and reject callbacks. Call resolve(value) on success and reject(reason) on failure.

Example
function delay(ms) {
  return new Promise(function(resolve) {
    setTimeout(resolve, ms);
  });
}
function fetchData(id) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      if (id > 0) resolve({ id: id, name: 'Item ' + id });
      else reject(new Error('Bad ID'));
    }, 200);
  });
}
fetchData(1)
  .then(function(data) {
    console.log(data.name); // Item 1
    return data.id * 10;
  })
  .then(function(val) {
    console.log(val); // 10
  })
  .catch(function(err) {
    console.error(err.message);
  })
  .finally(function() {
    console.log('done');
  });
Pro Tip

Always attach a .catch() at the end of every promise chain — an unhandled promise rejection can crash a Node.js process or generate a warning in browsers that will become an error in future versions.