Skip to content

Instantly share code, notes, and snippets.

@pgbytes
Created August 10, 2016 21:03
Show Gist options
  • Save pgbytes/a600629faf1f70c976195036f0247f4b to your computer and use it in GitHub Desktop.
Save pgbytes/a600629faf1f70c976195036f0247f4b to your computer and use it in GitHub Desktop.
Concept of nested promises
function getLocation() {
return new Promise(function (resolve, reject) {
resolve('Lucknow');
});
}
function getWeather(location) {
return new Promise(function (resolve, reject) {
resolve('It\'s 39 degrees in ' + location);
});
}
// Approach 2 tutorial
getLocation()
.then(function (location){
console.log('Acquired location is: ' + location);
return getWeather(location);
}).then( function (weather) {
console.log('Acquired weather info: ' + weather);
});
/**
* Approach 2 - tutorial approach (this is chaining)
* This is the correct approach, as
* getLocation method returns a promise, which is resolved by the `then` in line 14
* only after the getLocation promise is resolved, `getWeather` method is called which also returns a promise.
* the `then` at line 18 resolves the promise of getWeather method
* the return keyword will return the promise, else it will keep nesting.
* The main point to note is that the context of getLocation method is accesible in the block where getWeather method is called
* and is required as u need the result of getLocation method.
* But the context of getLocation method is not accessible in the .then function block where getWeather promise is resolved.
* That is fine as u do not need it.
* This is the recommended way of chaining the promises.
*/
// Approach 1 your approach (this is nesting)
getLocation().then(function (location) {
console.log('Acquired location is: ' + location);
getWeather(location).then(function (weather) {
console.log('Acquired weather info: ' + weather);
});
});
// if you write it formatted:
getLocation()
.then(function (location) {
console.log('Acquired location is: ' + location);
getWeather(location)
.then(function (weather) {
console.log('Acquired weather info: ' + weather);
});
});
/**
* (This is nesting)
* the `getLocation` method returns a promise.
* the .then at line 39 resolves the promise from getLocation method.
* then the getWeather method is called inside the getLocation block. Inside the getLocation context.
* the getWeather promise is resolved at line 42, but it is still inside the context of getLocation. which is not very good
* as u will want to keep the executions isolated from eachother, unless u want them to share the context. so it really
* depends on what u want to implment
*
* Both are right... but in this case, since they do not need to share the context, the nesting u made is not required.
* also makes it less testable.
*
* Moreover.. it is always good to include the return keyword.. else sometimes the code will behave in a strange way.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment