javascript - what is a correct angular pattern for returning multiple *independent* async results from a single service call -


i'm working on search ui. there list view of results , each result can "expanded" show more data. when user expands result, asynchronously fetch details can contain 0 12 pictures. done "detail service," service in angular sense.

now, because aiming "native feel" , these images can weighty, don't want them appear until have finished loading.

the question is: how service notify client (a controller) each image loads?

many articles recommend promises best way this. naively, think return array of promises - 1 each image - resolve after image loads.

this seems heavy-handed solution, requiring loop attaching then() functions arbitrary number of promises.

another popular solution use broadcast() on $rootscope. seems "sloppy" in know exactly "listening" result.

is "array of promises" correct, or there more concise or "angular" way?

note: these independent results , should not chained or composed single promise.

edit: apologize unclear ask. desired functionality each picture appears loaded. aggregating promises undesired. leaves core ask whether promises concise solve this. found think better one, expressed in answers image directive delays display until image loaded. moving logic out of service , directive seems more elegant solution.

i 'array of promises' correct approach.

you can use .all() method takes number of promises arguments (as array). can resolve promise single promise.

returns single promise resolved array/hash of values, each value corresponding promise @ same index/key in promises array/hash. if of promises resolved rejection, resulting promise rejected same rejection value.

    $q.all([firstpromise.then(function(){                              //do                              }),             secondpromise.then(function(){                              //do else                                })            ])      .then(function(){             //do after promises resolved             }); 

https://docs.angularjs.org/api/ng/service/$q


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -