diff --git a/README.md b/README.md index 20c9d63..da29580 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_667 TILs and counting..._ +_668 TILs and counting..._ --- @@ -253,6 +253,7 @@ _667 TILs and counting..._ - [Random Cannot Be Seeded](javascript/random-cannot-be-seeded.md) - [Reach Into An Object For Nested Data With Get](javascript/reach-into-an-object-for-nested-data-with-get.md) - [Render An Array Of Elements With React 16](javascript/render-an-array-of-elements-with-react-16.md) +- [Resolve And Pass Multiple Values From A Then](javascript/resolve-and-pass-multiple-values-from-a-then.md) - [Running ES6 Specs With Mocha](javascript/running-es6-specs-with-mocha.md) - [Scoping Variables With A Block Statement](javascript/scoping-variables-with-a-block-statement.md) - [Splat Arguments To A Function](javascript/splat-arguments-to-a-function.md) diff --git a/javascript/resolve-and-pass-multiple-values-from-a-then.md b/javascript/resolve-and-pass-multiple-values-from-a-then.md new file mode 100644 index 0000000..84669ba --- /dev/null +++ b/javascript/resolve-and-pass-multiple-values-from-a-then.md @@ -0,0 +1,39 @@ +# Resolve And Pass Multiple Values From A Then + +Let's say you are chaining multiple async function calls together. + +```javascript +fetchTrainer(trainerName) + .then(response => { + const trainerData = response.body; + + return fetchPokemonFor({ trainerId: trainerData.id }); + }) + .then(response => { + // I want trainerData, but it is now out of scope... + }); +``` + +But in the last `then()` you want access to both the `trainerData` and the +`pokemonData`. So, how do you pass both the `trainerData` and the resolved +response of `fetchPokemonFor()` through to that last `then()`. + +```javascript +fetchTrainer(trainerName) + .then(response => { + const trainerData = response.body; + + return Promise.all([ + trainerData, + fetchPokemonFor({ trainerId: trainerData.id }) + ]); + }) + .then(([trainerData, pokemonResponse]) => { + const pokemonData = pokemonResponse.body; + + // do something with trainerData and pokemonData + }); +``` + +`Promise.all` allows us to resolve and pass multiple promises. If any of the +values in the array argument is not a promise, it simply passes it through.