JavaScript Promises
JavaScript Basics

JavaScript Promises

JavaScript Promises: An Introduction

A JavaScript Promise is an object that represents a value that may not yet exist but is expected in the future. It connects asynchronous actions, which are the producing code (that may take time to execute) and the consuming code (which must wait for the result).

How Promises Work

A promise has three states:

  • Pending: The initial state of the promise. The outcome is not yet known.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Here’s how you create and use a promise:

Creating a Promise

let myPromise = new Promise(function(resolve, reject) 
{  
// Producing Code (might take time)‍
if (/* condition for success */) 
{    resolve("Success!"); // when the operation completes successfully  } 
else 

{   

reject("Failure!"); // when the operation fails  }});‍

// Consuming Code (must wait for a fulfilled Promise)myPromise.then(  function(value)

{ /* code if successful */ },  function(error) 
{ /* code if an error occurs */ }

);

In this structure:

  • resolve is the function called when the promise is fulfilled.
  • reject is called if the promise is rejected.
  • .then() method is used to specify what to do when the promise is fulfilled or rejected. This method takes two functions: one for success and one for failure.

Practical Promise Examples

Example: Set a Timeout with a Promise

let myPromise = new Promise(function(resolve) 
{  setTimeout(function() { resolve("I love you!!");
}, 3000);});‍myPromise.then(function(value) 

{  document.getElementById("demo").innerHTML = value;});‍
This example uses a promise to handle a timeout. The promise resolves after 3 seconds, updating the webpage content.

Example: Loading a File with a Promiselet loadFile = new Promise(function(resolve, reject)

{  let req = new XMLHttpRequest();  req.open('GET', "mycar.html");  req.onload = function() {    if (req.status == 200)

{      resolve(req.response); // Successfully loaded the file    } 

else {      reject("Error: " + req.statusText); // Failed to load the file    } 

};  req.onerror = function()
{    reject("Network Error");  };

req.send();});‍

loadFile.then(  function(content) 


{ document.getElementById("demo").innerHTML = content; },

function(error)

{ document.getElementById("demo").innerHTML = error; 

});

In this example, a promise manages the file loading process. The promise resolves if the file loads successfully and rejects if an error occurs.

Browser Support for Promises

Promises were introduced in ECMAScript 2015 (ES6) and are supported in:

  • Chrome 33+
  • Edge 12+
  • Firefox 29+
  • Safari 7.1+
  • Opera 20+

Advantages of Using Promises

  • Improved Error Handling: Promises provide better error handling in asynchronous JavaScript.
  • Avoid Callback Hell: Using promises can simplify nested callbacks, making the code easier to read and maintain.
  • Chain Asynchronous Operations: Promises can be chained, making it straightforward to perform several asynchronous operations back-to-back where each subsequent operation starts when the previous one ends.

Promises are a core component of modern JavaScript programming, especially for managing multiple asynchronous operations where callbacks can lead to complex, hard-to-manage code structures.

Take a look into your desired course