Created
June 8, 2017 04:43
-
-
Save antoniojps/0e9cc668d363faafe75885a825060a9a to your computer and use it in GitHub Desktop.
ES6 Promises
This file contains hidden or 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
/* | |
A promise is created with a resolve and reject function being | |
passed as arguments. Depending on the result, the appropriate function is | |
executed and a possible return value is passed as an argument. | |
*/ | |
let promise = new Promise((resolve,reject)=>{ | |
// then(func) | |
resolve('Ola!') | |
// catch(func) | |
reject(arg) | |
}) | |
promise.then(function(value) { | |
console.log(value); // Ola! | |
}); | |
////// Chained promises -> passam o valor automaticamente para a proxima | |
let fnWaitASecond = (secondsPassed) => { | |
return new Promise(function(resolve, reject) { | |
setTimeout(function() { | |
secondsPassed++; | |
resolve(secondsPassed); | |
}, 1000); | |
}); | |
}; | |
fnWaitASecond(0) | |
.then(fnWaitASecond) // Passa o argumento automaticamente para a proxima | |
.then(function(seconds) { | |
console.log('Promises: waited ' + seconds + ' seconds'); // 2 | |
}); | |
//// Metodo ALL | |
//// Para correr varias funcoes asincronas o melhor é usar o metodo .all | |
//// Testa todas as promises, combina todas as promises numa, apenas se todas forem resolvidas é que passa, se nao é rejected | |
//// Se todos forem resolved os argumentos tornam-se numa array dos argumentos de casa resolve ['Resolved!,'Resolved!] | |
let promise1 = new Promise((resolve,reject)=>{ | |
setTimeout(()=>{ | |
resolve('Resolved!'); | |
},1000) | |
}) | |
let promise2 = new Promise((resolve,reject)=>{ | |
setTimeout(()=>{ | |
reject('Rejected'); | |
},2000) | |
}) | |
Promise.all([promise1,promise2]) | |
.then(success=>{ | |
console.log(success) | |
}) | |
.catch(error=>{ | |
console.log(error) // Visto que a segunda promissa da erro chegaremos aqui "Rejected" | |
}) | |
//// Metodo Race | |
/// Se a primeira promessa funcionar corre o then, se TODAS nao funcionarem entao Catch | |
Promise.race([promise1,promise2]) | |
.then(success=>{ | |
console.log(value) // Resolved! | |
}) | |
.catch(error=>{ | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment