Table des matières

MIF38 - CM Promesses

Lionel Médini

MIF38 - Université Claude Bernard Lyon 1

licence Creative Commons BY-NC-SA

But de ce cours

Contenu de ce cours

Problème

Fonctions d'ordre supérieur

+

Programmation asynchrone

=

Callback hell

Source : http://callbackhell.com/

2 types de solutions

Promesses : définition

<note>“Promises provide a well-defined interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time.”</note>

Source : CommonJS

Outils pré-existants

→ Approches différentes

→ Syntaxes différentes

Unification

La notion (et surtout la syntaxe) unifiées sont les résultats de plusieurs synthèses :

Objectifs

Une promesse permet de :

…Tout en vous affranchissant de l'écriture du “boilerplate code”

Statuts

Une promesse est dans l'un des états suivants :

Workflow

Syntaxe

Création d'une promesse :

var p1 = new Promise(
    // The resolver function is called with the ability to resolve or reject the promise
    function(resolve, reject) {
      try {
        // ...
        if(touvabien) {
          // Fulfill the promise
          resolve(result);
        }  else {
          //Error
          reject(error);
        } catch(error) {
          reject(error);
        }
    });

Syntaxe

Utilisation d'une promesse :

p1.then(function(result) {
  //If fulfilled
}).catch(function(error) {
  //If rejected
}).done(funciton() {
  //If settled
});

Exemple

Attente de plusieurs promesses

Syntaxe (PromiseJS) :

var promises = [];
promises.push(p1);
promises.push(p2);
...
Promise.all(p).done(function(result) {
  //Can use all results
}

Exemple

Compétition entre promesses

Syntaxe (PromiseJS) :

var promises = [];
promises.push(p1);
promises.push(p2);
...
Promise.race(p).then(function(result) {
  //Can use all results
}

Exemple

Références