The Talent500 Blog

Talking with an External API using Promises in JavaScript

When we build a web application, we need other API resources to make a complete app, for example, categories or items for the e-commerce app. Otherwise, Building everything from scratch will cost more in terms of both money and time.

To save our precious time and money, it is a good idea to use external libraries or APIs in our application to build the desired functionality into our web application.

Now that we understand the use cases for external resources, we need to communicate with the corresponding APIs to utilize those resources in our application. In JavaScript, we can retrieve data from remote APIs using the fetch() method, which returns a promise.

So worry not, in this blog we will take a closer look at promises in JavaScript. Additionally, we will fetch the data from an API that will help us understand the practical use cases of promises. So without further ado, let’s get into this:

Overview of Promise

Promises are an essential feature introduced in ECMAScript 2015 (ES6) to handle asynchronous operations in JavaScript. They provide a more elegant and structured way of dealing with asynchronous code compared to traditional callbacks. 

Promises simplify the handling of asynchronous tasks and help avoid callback hell, making code more readable and maintainable.

A Promise represents the eventual completion or failure of an asynchronous operation and its resulting value. It acts as a placeholder for a value that may not be available yet but will be resolved in the future.

Asynchronous VS Synchronous code

Now let’s understand the difference between Asynchronous and synchronous code: they are two different approaches to executing code in JavaScript, especially when handling tasks that take time to complete, such as fetching data from an API, reading from a file, or waiting for user interaction.

How JavaScript Handles Promise States

JavaScript promise can have three states, whether the promise is pending, fulfilled, or rejected state. State refers to the current condition or state of a promised object.

Here is a simple illustration of the different states of the promise in JavaScript:

Let me explain these three states of the promise:

  1. Pending: This is the initial state of the promise, which means the async operation associated with the promise is still in progress and the final result has yet to be decided.
  2. Fulfilled: If the async operation has been completed successfully, then the promise changes from the pending state to the fulfilled state. It denotes that a promise has been resolved with a value. And now this value will be available for further processing.
  3. Rejected: If the error occurs during the async operation, then the promise changes from the pending state to the rejected state. It denotes that a promise has been rejected with an error object. Now this error object can be used to handle errors and display them on the page.

Note: When a promise is neither resolved nor rejected, we can say that it is pending.

How to Create a Promise

To create a promise in JavaScript, we can use the Promise constructor function. It takes the callback function as its argument, which has two parameters.

1. resolve: If the async operation is successful, we can call the resolve function and pass the result as an argument.

const asyncTask = new Promise(function (resolve, reject) {

  resolve(Hello);

  reject(Ooops!); //Ignored

});

console.log(asyncTask); // Promise {<fulfilled>: ‘Hello’}

asyncTask.then((data) => console.log(data)); // Hello

2. reject: If there is an error or the async operation fails, we can call the reject function and pass the error object as an argument.

const asyncTask = new Promise(function (resolve, reject) {

  reject(Ooops!);

  resolve(Hello); //Ignored

});

console.log(asyncTask); // Promise {<rejected>: ‘Ooops!’}

asyncTask.then((data) => console.log(data)); // Uncaught (in promise) Ooops!

How to Consume a Promise

Most of the time, we will consume the promises, which means talking with external APIs. To consume the result of the promise, we can use the then() method to handle a successful operation or the catch() method to handle a rejected operation.

Now we are going to use one of the most useful JavaScript fetch() API methods, which also returns a promise that can be resolved or rejected.

const asyncTask = fetch(https://fakestoreapi.com/products);

console.log(asyncTask); // Promise {<pending>}

An asyncTask is also a promise return by the fetch() method. Once we receive the response by the fetch(), we can use the then() method to handle it or catch() for the rejection.

Since it returns a promise, we still need to resolve it to use the content of the external resources in our application.

fetch(https://fakestoreapi.com/products)

  .then((res) => res.json())

  .then((data) => {

    console.log(data); //Data coming from an API

  });

The json() is used to extract the JSON (JavaScript Object Notation) content from a response obtained from an API request. 

It is an asynchronous method that returns a JavaScript Promise. When the Promise is fulfilled, it returns another Promise that resolves to a JavaScript object representing the JSON data from the response. Now we can use this data object in our application at a desired section of the page.

Chaining Promises

Chaining promises in JavaScript involves using the then() method to attach a callback function to a promise. 

This callback function will be executed when the promise is resolved, and it can return another promise. By returning a promise from the then() callback, we can chain multiple promises together, allowing one promise to depend on the result of another.

fetch(https://fakestoreapi.com/products)

  .then((res) => res.json())

  .then((data) => {

    console.log(data);

  });

The code snippets shown above involve the use of the then() method twice. The first instance of then() also results in a promise being returned. The second then the () method is reliant on the first one, which is known as “chaining of the promises” when multiple then() methods are dependent on each other.

All about then() method

In JavaScript, the then() method is a fundamental part of the Promises API, which is used for handling asynchronous operations. It is called on a Promise object and allows us to specify two different callbacks: 

  1. One for the case when the Promise is fulfilled (resolved) successfully.
  2. Another case is when the Promise is rejected (encounters an error).

Syntax of the then() method:

  promise.then(fulfilled, rejected)

Play with this codepen link and see the output in the console, however, we did not handle the error yet and also we have another way to achieve this goal using async and await keywords in JavaScript. So these topics will be discussed in the next blog, so keep connected with us.

Conclusion

Promises have become an important part of modern JavaScript development, providing a clean and efficient way to handle asynchronous operations. By understanding how promises work and utilizing chaining using the then() method. By leveraging the power of promises, JavaScript developers can unlock new levels of productivity and improve the overall user experience of their applications. Also, if you are looking for a JavaScript job, so please search them on talent500.co

 

1+