Created
October 8, 2014 20:38
-
-
Save sodiumjoe/bf6dcd019c3a99751633 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
/* | |
* Current pattern in console code | |
* does not leverage the power of promises | |
* may as well use callbacks | |
*/ | |
var _val1; | |
var _val2; | |
function apiCall() { | |
// some api call | |
} | |
apiCall().then(function(data) { | |
_val1 = data; | |
}); | |
// _val2 has implicit dependency on _val1 | |
// if _val1 is not loaded for some totally unrelated reason, this breaks | |
apiCall(_val1).then(function(data) { | |
_val2 = data; | |
}); | |
doSomeStuff(_val1, _val2); | |
/* | |
* Leveraging promises as representing values | |
*/ | |
var _val1Promise = apiCall(); | |
// _val2's dependency on _val1 is explicit | |
var _val2Promise = _val1Promise.then(apiCall); | |
Promise.all(_val1Promise, _val2Promise).then(function(vals) { | |
doSomeStuff(vals[0], vals[1]); | |
}); | |
_val1Promise.then(function(val1) { | |
doAnotherThing(val1); | |
}); | |
// now I can use val2 without having to worry about whether val1 is loaded | |
_val2Promise.then(function(val2) { | |
doAnotherThing(val2); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment