A beginners guide to understanding JavaScript Promises

Get a better understanding of JavaScript Promises

Promises in JavaScript are one of those topics where you find it hard to wrap your head around as a beginner. In this article, I'm going to help you with that. We will learn about promises and some of their common use cases with examples.

Buckle up and get ready for this wild ride.

Synchronous vs Asynchronous Code

Before we dive into promises, let me get it clear about Synchronous vs Asynchronous Code.

JavaScript's synchronous code executes statements in the order they are written, one after the other. This means that before the next statement can start, the previous one must be finished.

Synchronous Code Example

console.log('Hello')
console.log('World')
//results
>> Hello
>> World

In contrast, asynchronous code allows multiple operations to run concurrently and does not block the execution of subsequent statements. Asynchronous operations typically include things like timers, network requests, file I/O, and user interactions.

In JavaScript, asynchronous code is executed using callback functions, promises, or async/await syntax. The use of asynchronous programming enables JavaScript to handle many tasks at once, improving performance and allowing for more responsive user interfaces.

Asynchronous Code Example

console.log('Before setTimeout');

setTimeout(function() {
  console.log('setTimeout has completed');
}, 2000);

console.log('After setTimeout');

//results
>> 'Before setTimeout'
>> 'After setTimeout'
>> 'setTimeout has completed'

Promises Explained

A promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. A promise can be in one of 3 states: pending, fulfilled, or rejected. It starts in the pending state and transitions to either fulfilled (resolved) or rejected, once the asynchronous operation completes or fails. A promise can be used to handle the completion or failure of an asynchronous operation in a more intuitive and organized manner.

A commonly used analogy for JavaScript promises is a restaurant reservation scenario. When you make a reservation at a restaurant, you are given a promise that a table will be available for you at the specified time. The restaurant either keeps its promise and has a table ready for you, or it fails to keep the promise and does not have a table available. In the same way, a JavaScript promise represents a value that may not be available yet, and it either resolves (fulfils) the value or rejects it with an error. This pattern enables cleaner, more readable code by providing a way to handle asynchronous operations in a more intuitive and organized manner.

Common Use Cases of JavaScript Promises

Fetching Data from an API

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

Perform multiple async operations in a specific order

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    return fetch(`https://api.example.com/data/${data.id}`);
  })
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

Reading a file from a disk

const fs = require('fs');

function readFile(file) {
  return new Promise((resolve, reject) => {
    fs.readFile(file, 'utf-8', (error, data) => {
      if (error) {
        reject(error);
      } else {
        resolve(data);
      }
    });
  });
}

readFile('example.txt')
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

In conclusion, JavaScript Promises provide a more efficient and straightforward way to handle asynchronous operations in comparison to callbacks. With Promises, we can write cleaner code, avoid callback hell, and handle errors more effectively. As Promises are widely supported by modern browsers and libraries, they have become a fundamental concept for developers to master. By leveraging the power of Promises, we can build better and more robust applications.

I hope this article helped you get an overall idea about JavaScript promises.