Created
April 24, 2017 23:50
-
-
Save ajchambeaud/845afc1c1f261983e9f8dab733b6de6d to your computer and use it in GitHub Desktop.
Promise.All Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Function simple que retorna una promise | |
function add(a, b) { | |
/** | |
* Alias para: | |
* | |
* return new Promise((resolve, reject) => resolve(a + b)); | |
*/ | |
return Promise.resolve(a + b); | |
} | |
// Function simple que retorna una promise fallando siempre | |
function addFail(a, b) { | |
/** | |
* Alias para: | |
* | |
* return new Promise((resolve, reject) => reject(new Error("No se sumar!"))); | |
*/ | |
return Promise.reject(new Error('No se sumar!')); | |
} | |
// Multiples llamadas en paralelo a operaciones async | |
Promise.all([add(2, 3), add(4, 5), add(5, 7)]) | |
.then(([r1, r2, r3]) => { | |
const result = r1 + r2 + r3; | |
console.log(result); | |
}) | |
.catch(error => { | |
console.log(`Fail! ${error}`); | |
}); | |
/** | |
* Promise.all resolved implica que todas las operaciones fueron exitosas, | |
* Si una falla, sale por el catch | |
*/ | |
Promise.all([add(2, 3), addFail(4, 5), add(5, 7)]) | |
.then(([r1, r2, r3]) => { | |
const result = r1 + r2 + r3; | |
console.log(result); | |
}) | |
.catch(error => { | |
console.log(`Fail! ${error}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment