javascript - Accessing a previously fullfilled promise result in a promises chain -


this question has answer here:

what correct pattern, when coding promises, access data coming long before in chain of promises?

for example:

do_a.then(do_b).then(do_c).then(do_d).then(do_e_withthedatacomingfrom_a_and_c_onlywhen_d_issuccesfullycompleted) 

my current solution: passing along single json structure through chain, , let each step populate it. opinion that?

i don't think there's 1 "correct" pattern this. solution sounds neat, however, it's bit tightly coupled. may work great situation, see few problems general pattern:

  1. participating steps need agree on structure of collector object.

  2. every step needs participate in @ least forwarding of object, can tedious if chain long , need previous data occurs sporadically. inflexible insertion of steps not written (chaining doesn't happen linearly).

  3. said differently: unless do_a|b|c|d , do_e under control, you'll need wrap them boilerplate store off collector object in closure , convert , functions' natural inputs , results, since functions wont "in on" pattern.

  4. on other hand, if functions are in on it, data-dependencies between steps have become hidden inside functions. may clean, become maintenance problem. example: if team project, might think can re-order steps, absent no clue in call-pattern inputs do_e requires.

i suggest more straightforward approach using closures:

var a, c;  do_a() .then(function(result) { = result; return do_b(); }) .then(do_c) .then(function(result) { c = result; return do_d(); }) .then(function() {    return do_e_withthedatacomingfrom_a_and_c_onlywhen_d_succeeds(a, c); }) .catch(failed); 

there's no collector object define; do_a|b|c|d , do_e can generic functions without knowledge of pattern; there's no boilerplate unless returned data relied on (do_b , do_d); , data-dependencies (a , c) explicit.


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -