From efbe761353a0ed954402f21756f4bdf15c7b3823 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 9 Feb 2018 10:05:12 -0600 Subject: [PATCH] Add Waiting On Multiple Promises as a javascript til --- README.md | 3 +- javascript/waiting-on-multiple-promises.md | 39 ++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 javascript/waiting-on-multiple-promises.md diff --git a/README.md b/README.md index 54e4e5e..7fac441 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/). -_609 TILs and counting..._ +_610 TILs and counting..._ --- @@ -242,6 +242,7 @@ _609 TILs and counting..._ - [Timing Processes](javascript/timing-processes.md) - [Transforming ES6 and JSX With Babel 6](javascript/transforming-es6-and-jsx-with-babel-6.md) - [Truthiness of Integer Arrays](javascript/truthiness-of-integer-arrays.md) +- [Waiting On Multiple Promises](javascript/waiting-on-multiple-promises.md) - [Yarn Commands Without The Emojis](javascript/yarn-commands-without-the-emojis.md) ### Linux diff --git a/javascript/waiting-on-multiple-promises.md b/javascript/waiting-on-multiple-promises.md new file mode 100644 index 0000000..340b9aa --- /dev/null +++ b/javascript/waiting-on-multiple-promises.md @@ -0,0 +1,39 @@ +# Waiting On Multiple Promises + +You may find yourself in a situation where you have to request multiple +resources from multiple API endpoints and then combine that data in some +way. + +One way to achieve this would be with nested promises. + +```javascript +fetch('/blogs').then((response) => { + let blogs = response.body; + + fetch('/tags').then((response) => { + let tags = response.body; + + // combine blogs and tags ... + }) +}) +``` + +This nesting isn't ideal and it can get hard to read as the full +implementation is put into place. + +The `Promise` API provides an alternative. + +```javascript +let blogsPromise = fetch('/blogs') +let tagsPromise = fetch('/tags') + +Promise.all([blogsPromise, tagsPromise]).then(([blogsResp, tagsResp]) => { + // combine blogs and tags ... +}) +``` + +With +[`Promise.all()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) +we are able to wrap any number of promises and wait for all of them to +resolve until we do something with the results. This allows us to create a +context in which we have all the data we need without a bunch of nesting.