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:

  • pending - this is the start state (ie when the final value is not available yet)
  • then:
    • resolved (ie fulfilled) - via the resolve function that associate a value to the promise.
    • or rejected via the reject function or when an error prevented the final value from being determined.

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:

  • a value
  • or an error

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





Discover More
Chrome Devtool Xhr Fetch Request
Browser - Web API - Fetch function

The fetch function is part of the web api function and is a AJAX call. It's one of the possibilities to fetch a resource. XMLHttpRequest (XHR) The fetch function returns a promise as response. The Fetch...
Javascript - Asynchrony

This page is Asynchrony in javascript. Asynchrony is not only critical to the performance of our applications, but it’s also increasingly becoming the critical factor in writability and maintainability....
Javascript - Await and Async Syntax

await and async is the second promise syntax that permits to manipulate promise. The async/await syntax is part of ECMAScript 2017 and reduces the callback nesting find in the chaining syntax. The...
Javascript Console Pause On Exception
Javascript - Exception Handling with the Error object

This page is exception in Javascript Exceptions can be caught: in a try, catch, throw, finally statement. with the catch function with a promise. See catch...
Javascript - Generator

A generator is a function implementation of an iterator pattern. When instantiated, you can get the next value with the next().value statement. with a promise ...
Javascript - Promise Chaining

promise chaining is one of the two promise syntax to manipulate promise The promise function addOne that will add one. The chain The creation of a promise is done via a constructor that...
Jest - Mock

in Jest Mocking is just replacing a function by another called a mocking function. In Jest mocking function can replace the code executed but they also record all call made to them creating a command...
Card Puncher Data Processing
MySql - Node

before 8.0: mysql Tip: To be able to have NULL value, you need to declare the column NULLABLE. See test-type-cast-null-fields.js...
Card Puncher Data Processing
Observable

Cells is the notebook are named and are then variable hosting a function or a value (as javascript does) Cells can be: expressions blocks. { } an object literal ({ }) Example a cell named letters:...
Browser
Puppeteer - Javascript page injection

How to expose, inject javascript function in a Puppeteer page Puppeteer communicate with the browser via the DevTools Protocol (Chrome Debugging Protocol.)....



Share this page:
Follow us:
Task Runner