Skip to content

Instantly share code, notes, and snippets.

@marta-krzyk-dev
Last active April 27, 2019 20:48
Show Gist options
  • Save marta-krzyk-dev/7d475e052dab0101204fa452c1e5c94d to your computer and use it in GitHub Desktop.
Save marta-krzyk-dev/7d475e052dab0101204fa452c1e5c94d to your computer and use it in GitHub Desktop.
Promises all and race in JS
//From: https://www.youtube.com/watch?v=s6SH72uAn3Q
{ //Declare scope
let cleanRoom = function(message) {
return new Promise(function(resolve, reject) {
resolve(message + ' I cleaned the room!');
});
};
let removeGarbage = function(message) {
return new Promise(function(resolve, reject) {
resolve(message + ' I removed garbage!');
});
};
let winIceCream = function(message) {
return new Promise(function(resolve, reject) {
resolve(message + ' I won ice cream!');
});
};
cleanRoom.then(function(result){
return removeGarbage(result);
}).then(function(result) {
return winIceCream(result);
}).then(function(result){
console.log('I\'m finished! ' + result);
});
Promise.all([cleanRoom(), removeGarbage(), winIceCream()])
.then(function(){
console.log('All finished!!');
});
Promise.race([cleanRoom(), removeGarbage(), winIceCream()])
.then(function(){
console.log('At least one of them is finished!!');
});
} // End scope
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment