Skip to content

Commit 48c62e2

Browse files
committed
Add Resolve And Pass Multiple Values From A Then as a javascript til
1 parent 570ffe2 commit 48c62e2

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010
For a steady stream of TILs from a variety of rocketeers, checkout
1111
[til.hashrocket.com](https://til.hashrocket.com/).
1212

13-
_667 TILs and counting..._
13+
_668 TILs and counting..._
1414

1515
---
1616

@@ -253,6 +253,7 @@ _667 TILs and counting..._
253253
- [Random Cannot Be Seeded](javascript/random-cannot-be-seeded.md)
254254
- [Reach Into An Object For Nested Data With Get](javascript/reach-into-an-object-for-nested-data-with-get.md)
255255
- [Render An Array Of Elements With React 16](javascript/render-an-array-of-elements-with-react-16.md)
256+
- [Resolve And Pass Multiple Values From A Then](javascript/resolve-and-pass-multiple-values-from-a-then.md)
256257
- [Running ES6 Specs With Mocha](javascript/running-es6-specs-with-mocha.md)
257258
- [Scoping Variables With A Block Statement](javascript/scoping-variables-with-a-block-statement.md)
258259
- [Splat Arguments To A Function](javascript/splat-arguments-to-a-function.md)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Resolve And Pass Multiple Values From A Then
2+
3+
Let's say you are chaining multiple async function calls together.
4+
5+
```javascript
6+
fetchTrainer(trainerName)
7+
.then(response => {
8+
const trainerData = response.body;
9+
10+
return fetchPokemonFor({ trainerId: trainerData.id });
11+
})
12+
.then(response => {
13+
// I want trainerData, but it is now out of scope...
14+
});
15+
```
16+
17+
But in the last `then()` you want access to both the `trainerData` and the
18+
`pokemonData`. So, how do you pass both the `trainerData` and the resolved
19+
response of `fetchPokemonFor()` through to that last `then()`.
20+
21+
```javascript
22+
fetchTrainer(trainerName)
23+
.then(response => {
24+
const trainerData = response.body;
25+
26+
return Promise.all([
27+
trainerData,
28+
fetchPokemonFor({ trainerId: trainerData.id })
29+
]);
30+
})
31+
.then(([trainerData, pokemonResponse]) => {
32+
const pokemonData = pokemonResponse.body;
33+
34+
// do something with trainerData and pokemonData
35+
});
36+
```
37+
38+
`Promise.all` allows us to resolve and pass multiple promises. If any of the
39+
values in the array argument is not a promise, it simply passes it through.

0 commit comments

Comments
 (0)