Skip to content

Instantly share code, notes, and snippets.

@jessemoon0
Last active November 23, 2016 23:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessemoon0/43edc36026f60d02e5b607482032c26e to your computer and use it in GitHub Desktop.
Save jessemoon0/43edc36026f60d02e5b607482032c26e to your computer and use it in GitHub Desktop.
2nd Example of a JS Promise: A cleaner code in case you have many callbacks in your JS.
//Promise Dependencies (after promiseExplanation)
//In this Example first you clean the room, then remove the garbage and finally win an icecream.
//Here also im directly resolving the promises, real life is code and check if resolved or reject.
let cleanRoom = function(){
return new Promise(function(resolve, reject){
resolve('I Cleaned the Room');
});
};
let removeGarbage = function(message){
return new Promise(function(resolve, reject){
resolve(message + ' then I removed Garbage');
});
};
let winIceCream = function(message){
return new Promise(function(resolve, reject){
resolve(message + ' So I won an Icecream!');
});
};
//Executing dependant functions
cleanRoom().then(function(result){ //Executes cleaning the room and if its resolved...
//Remember that the result argument is to carry the resolve.
return removeGarbage(result); //Executes remove the garbage and if its resolved...
}).then(function(result){
return winIceCream(result); //Executes winning an Icecream!
}).then(function(result){ //If Icecream is resolved...
console.log('Finished: ' + result); //log the price to console!
});
//Promise.all only excecutes after all promises inside has succesfully finished
Promise.all([cleanRoom(), removeGarbage(), winIceCream()]).then(function(){
console.log('All finished');
});
//Promise.race excecutes if any of the promises inside has succesfully finished
Promise.race([cleanRoom(), removeGarbage(), winIceCream()]).then(function(){
console.log('One has finished');
});
@jessemoon0
Copy link
Author

To see results: Check in JSFiddle and open the dev tools console.

@jessemoon0
Copy link
Author

Notice that when running, promises.all and promises.race executes before the dependencies (I think .all and .race is faster code)...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment