HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Promises

A Promise is a JavaScript object that links "Producing Code" and "Consuming Code". Producing code is code that can take some time. Consuming code is code that must wait for the result.


Promise States

A JavaScript Promise object can be in one of three states:

  • Pending: Evaluation is not yet complete (initial state).
  • Fulfilled (Resolved): The result is successfully completed.
  • Rejected: An error occurred during evaluation.

Promise Syntax

let myPromise = new Promise(function(myResolve, myReject) {
  // "Producing Code" (May take time)

  if (success) {
    myResolve("OK"); // Success!
  } else {
    myReject("Error"); // Failure!
  }
});

// "Consuming Code" (Must wait for a settled Promise)
myPromise.then(
  function(value) { /* success */ },
  function(error) { /* error */ }
);

Using then() and catch()

For better readability, most developers use .then() for success and .catch() for errors.

myPromise
  .then(value => console.log(value))
  .catch(error => console.log(error));

Real-world Example (Simulation)

let dataFetch = new Promise((resolve, reject) => {
  let success = true;
  setTimeout(() => {
    if (success) resolve("Data Loaded!");
    else reject("Server Error");
  }, 2000);
});

dataFetch.then(res => console.log(res)); 
Why use Promises? Promises are cleaner than callbacks because they allow for chaining and centralized error handling (no more "Callback Hell").

Key Points to Remember

  • A Promise represents a value that will be available in the future
  • They prevent deep callback nesting
  • There are three states: Pending, Fulfilled, or Rejected
  • Use resolve() to finish successfully and return data
  • Use reject() to return an error reason
  • Consume results using .then() and .catch()
  • Perfect for API fetching and file reading