Guest User

Untitled

a guest
Jul 17th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. ## Concurrency with Promises
  2.  
  3. window.Promise provides some helpful functions for dealing with multiple Promises at once. Let's look at some of the most useful ones.
  4.  
  5. ## Promise.all( iterableOfPromises )
  6.  
  7. Promise.all takes in an iterable (we'll use arrays in these examples) of Promises and will not resolve until all of the Promises in the array have resolved. When they have all resolved, the first then will receive an array of resolved Promises that you can do whatever you want with.
  8.  
  9. ```js
  10. const p1 = fetch('/user/1');
  11. const p2 = fetch('/contributions/1');
  12. Promise.all([p1, p2])
  13. .then(([user, contributions]) => { }); // Do something with this user and their contributions
  14. .catch(rejected => console.log(rejected));
  15. ```
  16.  
  17. There are a few interesting things to note here. First, I'm using array decomposition in the then and catch functions to make things a bit easier to work with. Second is that the catch will receive only the result of the Promise that rejected - further to this, Promise.all will fail fast, so if one Promise rejects the Promise.all will instantly reject and give the result of the rejected promise to the catch function, if you provided one. From some quick testing it seems that only the first rejected Promise in the array will be given to the catch.
  18.  
  19. ## Promise.race( iterableOfPromises )
  20.  
  21. Promise.race also takes in an iterable, just like Promise.all. However, as you may be able to guess from the name, it does not resolve with a new array of all of the results, it just resolves with the result of the Promise that finished the quickest. Use cases for this one include getting data from multiple sources and giving back whichever one finished the fastest, say if you were hitting your localStorage as well as making an API call.
  22.  
  23. ```js
  24. const p1 = new Promise(function (resolve, reject) {
  25. setTimeout(resolve, 200, 'two');
  26. });
  27. const p2 = new Promise(function (resolve, reject) {
  28. setTimeout(resolve, 100, 'one');
  29. });
  30. Promise.race([p1, p2]).then(result => console.log(result)); // 'one' will be printed to the console
  31. ```
  32.  
  33. ### That's all...?
  34.  
  35. I thought there were more but in doing more research for this course they seem to have been removed. They were definitely much less useful than these two, by far!
Add Comment
Please, Sign In to add comment