Table of Contents

Javascript - Promise Function

About

Data Concurrency - Promise in the Javascript context

A promise is a function that encapsulate a executor function in order to:

A promise is one way of enabling asynchrony in Javascript.

ajax function returns generally a promise.

Concept

Syntax

The promise mechanism has two syntax:

Creation

The creation of a promise starts immediately an encapsulated function called the executor asynchronously (ie started in other thread)

Example:

promise = new Promise( executor(resolve, reject) ) )
promise = async executor

Executor

The executor function is the function started at the creation of the promise.

With:

State

A promise may be in three state:

Little demo to see the state (this demo must be run in the devtool via F12)

// Promise already resolved to go quick
var resolvedPromisesArray = [Promise.resolve(1), Promise.resolve(2)];

// Try to resolve them again
var p = Promise.all(resolvedPromisesArray);
// immediately logging the value of p should show a pending state
console.log(p);

// using setTimeout we can execute code later
setTimeout(function() {
    console.log(p); // should show a pending resolved
});

Javascript Es Promise State

Resolve

Resolve is a in the context of a promise means that the execution of the executor function has ended without error and has returned a value.

It's also the name of the function that is:

Example and Snippet of the executor

executor(resolve, reject) => {
  if (allGood) {
     resolve(someValue); // The promise is resvoled (ie fulfilled) - The value may be of any type, including undefined.
  } else {
     reject("failure reason"); // rejected - The value may be any type, including undefined, though it is generally an Error object, like in exception handling.
  }
}

Fulfillment

Once the executor function has been executed (fulfilled), you can retrieve either:

Get the value

Get the error

Lifecycle Example

with the async/await syntax

fn = async function (i) {
    console.log("Promise "+i+" was started");
    return i+1;
};

(async () => {
 
  promises = []
  console.log("Creation of the promises");
  for (var i = 0; i < 5; i++) {
    promises.push(fn(i));
  };
  console.log(" ");
  
  console.log("We got back promises object");
  for (var i = 0; i < promises.length; i++) {
    console.log(promises[i].constructor);
  };
  console.log(" ");
  
  console.log("We unwrap the promise and get the result");
  for (var i = 0; i < promises.length; i++) {
    console.log(await promises[i]);
  };
  console.log(" ");
  

})();

Documentation / Reference