Lionel Médini
MIF38 - Université Claude Bernard Lyon 1
Fonctions d'ordre supérieur
+
Programmation asynchrone
=
Source : http://callbackhell.com/
<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
→ Approches différentes
→ Syntaxes différentes
La notion (et surtout la syntaxe) unifiées sont les résultats de plusieurs synthèses :
Une promesse permet de :
…Tout en vous affranchissant de l'écriture du “boilerplate code”
Une promesse est dans l'un des états suivants :
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);
}
});
Utilisation d'une promesse :
p1.then(function(result) {
//If fulfilled
}).catch(function(error) {
//If rejected
}).done(funciton() {
//If settled
});
Syntaxe (PromiseJS) :
var promises = [];
promises.push(p1);
promises.push(p2);
...
Promise.all(p).done(function(result) {
//Can use all results
}
Syntaxe (PromiseJS) :
var promises = [];
promises.push(p1);
promises.push(p2);
...
Promise.race(p).then(function(result) {
//Can use all results
}