Created
December 28, 2016 12:35
-
-
Save sushanthmangalore/a56a03565d4e409891a3498785c178f2 to your computer and use it in GitHub Desktop.
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 add(xPromise,yPromise) { | |
// `Promise.all([ .. ])` takes an array of promises, and returns a new promise that waits on them all to finish | |
return Promise.all( [xPromise, yPromise] ) | |
// when that promise is resolved, let's take the received `X` and `Y` values and add them together. | |
.then( function(values){ | |
// `values` is an array of the messages from the previously resolved promises | |
return values[0] + values[1]; | |
}); | |
} | |
// `fetchX()` and `fetchY()` return promises for their respective values, which may be ready | |
add( fetchX(), fetchY() ) | |
// we get a promise back for the sum of those two numbers. now we chain-call `then(..)` to wait for the resolution of that returned promise. | |
.then( function(sum){ | |
console.log( sum ); // that was easier! | |
}); | |
function fetchX(){ | |
return new Promise(function(resolve,reject){ | |
resolve(5); | |
}); | |
} | |
function fetchY(){ | |
return new Promise(function(resolve,reject){ | |
resolve(6); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment