javascript - Simplifying nested promises and loops -


i'm building angular app , i'm trying understand better promises when i'm dealying async calls (like $http) wrap them in service call them in controllers this:

...  function whatever(arguments) {     dataservice.getuser(arguments)         .then(onusercomplete)         .then(dataservice.getextra)         .then(onextracomplete)         .catch(onerror);      function onusercomplete(user) {         //do user         ...         // return user id (because         // supposing getextra         // requiring id argument)         return user.id;     }      function onextracomplete(extra) {         //         // no need return anything,         // last element of         // chain.     }      function onerror(error) {         console.log(error);     } }  ... 

this me keeping every function understandable , maintenable, easy read , consistent... @ least until need deal collection. suppose need same thing before, instead of having 1 user, i'm getting entire collection of user (and still need obtain data of each single user). did this:

...  function whatever(arguments) {     dataservice.getusers(arguments)         .then(onuserscomplete)         .catch(onerror);      function onuserscomplete(users) {         users.foreach(function(user) {             dataservice.getextra(user.id)                 .then(onextracomplete)                 .catch(onerror);         });     }      ... }  ... 

is best can obtain trying follow coding style? possible resolve problem single promise chain? thanks

you can use promise.all (documentation) wait array of promises.

dataservice.getusers(arguments)     .then(users => users.map(         user => dataservice.getextra( user.id )     ))     .then( promise.all )     .then( user_extra => /* array user data result */ )     .catch( onerror ); 

we map users array of promises returned function, use promise.all bundle promises. in next .then() user data loaded , provided in result array.


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -