techStackGuru

Javascript Promises


Promis are objects that represent asynchronous operations and their results after they are completed (or failed). Asynchronous operations such as fetching data from an API, reading files, and querying databases can be handled by promises.

There are three states of promises:

  • Pending - This is the initial state when the promise is created and the asynchronous operation is still occurring.
  • Fulfilled - The promise's result (or value) has been delivered successfully after the asynchronous operation was completed.
  • Rejected - An operation that fails with an error (or reason) for the failure.
  • Promises can be created using the Promise constructor. There are two parameters, commonly referred to as resolve and reject, that are passed as arguments to the function.

    Example 1

    let promise = new Promise(function(resolve, reject) {
        setTimeout(() => resolve("Task Completed"), 1000);
      });
      
      promise.then(
        function(result) { console.log("Result",result) }, // Will Run
        function(error) { console.log("Error",error) }
      ); 

    Example 2

    let promise = new Promise(function(resolve, reject) {
        setTimeout(() => reject("Task Failed"), 1000);
      });
      
      promise.then(
        function(result) { console.log("Result",result) },
        function(error) { console.log("Error",error) } // Will Run
      ); 

    Example 3

    let promise = new Promise(function(resolve, reject) {
        setTimeout(() => resolve("Task Completed"), 1000);
      });
      // resolve runs the first function in .then
      promise.then(
        result => console.log("Result",result), // Will Run
        error => console.log("Error",error) //  Will Not Run
      );
      
      // Alernate Way
      let promise = new Promise(function(resolve, reject) {
        setTimeout(() => resolve("Task Completed"), 1000);
      });
      promise.then(
        function(result) { console.log("Result",result) }, // Will Run
        function(error) { console.log("Error",error) } //  Will Not Run
      ); 

    Example 4

    let promise = new Promise(function(resolve, reject) {
        setTimeout(() => reject("Task Completed"), 1000);
      });
      // resolve runs the first function in .then
      promise.then(
        result => console.log("Result",result), // Will Not Run
        error => console.log("Error",error) //  Will Run
      );
      
      // Alernate Way
      let promise = new Promise(function(resolve, reject) {
        setTimeout(() => reject("Task Completed"), 1000);
      });
      promise.then(
        function(result) { console.log("Result",result) }, // Will Run
        function(error) { console.log("Error",error) } //  Will Not Run
      ); 

    Example 5

    function makeAPICall(url) {
        return fetch(url)
          .then(response => {
            if (!response.ok) {
              throw new Error('Network response was not ok');
            }
            return response.json();
          });
    }
    // Example usage:
    makeAPICall('https://jsonplaceholder.typicode.com/users/1')
        .then(data => {
        console.log("Response",data); // API response data
        })
        .catch(error => {
        console.error("Error",error);
    }); 

    A GET request to the specified URL is made using the fetch function in this example. Upon successful completion of the fetch function, a promise is returned that resolves to the Response object.

    As part of the .then() method, we check if the response was successful (status code ranging from 200 to 299). It fails if the network response is not ok, so we throw an error using throw new Error('Network response was not ok').

    Upon successful completion, we can retrieve the parsed JSON data by calling the .json() method on the Response object.

    Example 6 - Delaying Execution:

    function delay(ms) {
        return new Promise(resolve => {
            setTimeout(resolve, ms);
        });
     }
    
     // Example usage:
     console.log('Start');
        delay(2000)
        .then(() => {
            console.log('Two seconds have passed');
     }); 

    As shown in this example, the delay function returns a promise that resolves after a defined amount of time. To delay the promise, it uses setTimeout, and the promise resolves when the timeout expires. It can be useful when a delay is needed before executing subsequent steps or when execution needs to be paused.

    Example 7 - Reading a File:

    function readFile(file) {
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.onload = event => {
            resolve(event.target.result);
          };
          reader.onerror = event => {
            reject(new Error('Error reading file'));
          };
          reader.readAsText(file);
        });
      }
      
      // Example usage:
      const myFile = document.querySelector('#myFileInput').files[0];
      readFile(myFile)
        .then(fileContent => {
          console.log(fileContent); // Process the file content
        })
        .catch(error => {
          console.error(error);
        }); 

    Here, the readFile function uses the FileReader API to read the content of a file. When the file is successfully read, the promise resolves with the file content; otherwise, it rejects with an error message. Once the file content has been read, .then() can process it.