Skip to content

Instantly share code, notes, and snippets.

@sodiumjoe
Created October 8, 2014 20:38
Show Gist options
  • Save sodiumjoe/bf6dcd019c3a99751633 to your computer and use it in GitHub Desktop.
Save sodiumjoe/bf6dcd019c3a99751633 to your computer and use it in GitHub Desktop.
/*
* 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