Guest User

Untitled

a guest
Jun 21st, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. How do I execute something after all promises within a loop have resolved?
  2.  
  3. Example code:
  4. ``` javascript
  5.  
  6. // ... url, headers, parameters for the requests
  7.  
  8. // Item we are iterating over and we actually use within the requests
  9. var example = {
  10. 'Weekly',
  11. 'Monthly',
  12. 'Yearly'
  13. };
  14.  
  15. // Set up empty results object
  16. var results = {};
  17.  
  18. // Loop over filters and create two queries for each filter
  19. Object.keys( example ).forEach( ( filter, index ) => {
  20.  
  21. // ... Preparing parameters depending on currently looped item
  22.  
  23. // Make first request
  24. makeRequest( url, headers, 'GET', parameters )
  25. .then( ( data ) => {
  26.  
  27. // ... Doing stuff with data depending on currently looped item
  28. var firstData = data;
  29.  
  30. // Make another request with other parameters
  31. return makeRequest( endpoint, headers, 'GET', parameters );
  32.  
  33. } )
  34. .then( ( data ) => {
  35.  
  36. // Add both things to resultsBuild results array
  37. results[ filter ] = {
  38. first: firstData,
  39. second: data
  40. };
  41.  
  42. if ( index === Object.keys( example ).length - 1 )
  43. exampleCallbackMethod( results ) // This should only be executed when the for loop is finished and all promises are resolved
  44.  
  45. } )
  46. .catch( ( error ) => {
  47.  
  48. console.error( error );
  49.  
  50. } );
  51.  
  52. } );
  53. ```
Add Comment
Please, Sign In to add comment