Skip to content

Instantly share code, notes, and snippets.

@rayhon1014
Last active April 10, 2017 23:48
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 rayhon1014/59b2d6228a78567cd6d1ec065f1b61ec to your computer and use it in GitHub Desktop.
Save rayhon1014/59b2d6228a78567cd6d1ec065f1b61ec to your computer and use it in GitHub Desktop.
// 2 problems for the code below:
// (1) use somethingAsync(function(err, result)) format that could swallowed up the error in the nested call.
// (2) nested async call as a whole can be flattened out
firstThingAsync().then(function(result) {
// handle success but any error coming from secondThingAsync() will be swallowed
secondThingAsync().then(function(result2) {
// do something with result1 and result2
});
},
function(err) {
// handle error
});
// avoid somethingAsync(function(err, result)) format and use catch for error handling after then()
somethingAsync()
.then(function(result) {
// handle success
})
.catch(function(err) {
// handle error
});
// to avoid nested promise you can use promise.all(list) that will have all async calls run in parallel
Promise.all([firstThingAsync, secondThingAsync])
.then(function(results) {
// do something with result1 and result2
// available as results[0] and results[1] respectively
})
.catch(function(err) { /* ... */ });
// if you need the result from first call for the 2nd call, you can do the following
firstThingAsync()
.then(function(result1) {
return Promise.all([result1, secondThingAsync(result1)]);
})
.then(function(results) {
// do something with results array: results[0], results[1]
})
.catch(function(err){ /* ... */ });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment