0

I have to deal with long promise chains and subchains returned by function calls to semi-external libraries. I've run into a situation where I have to access value from a subchain from another subchain (simplified example below).

I'd like to achieve getting/querying a value that some previous promise has set without having to manually pass that value through every promise in the chain. This value doesn't have to be a return value, if that helps anything.

What would be the best practice for doing this? Note that since we're living in an async world, multiple instances of the same chain may be processing simultaneously...

function doNothing {
   return true;
}

function setValue {
   // somehow set <some> property to '1234'
}

function accessValue {
   // somehow read from <some> property '1234'
}

Q( true ).then( doNothing )
   .then( doNothing )
   .then( doNothing )
   .then( function() {
       return Q( true ).then( doNothing ).then( setValue ).then( doNothing );
   } )
   .then( function() {
       return Q( true ).then( doNothing ).then( accessValue ).then( doNothing );
   } )
   .done();
Salieri
  • 782
  • 6
  • 17
  • There are cases where subchains are fed from another module. Closures won't solve that. – Salieri Aug 12 '14 at 18:02
  • If intermediate values are inaccessible because they are used inside another module that doesn't publish them, they will stay inaccessible anyway. – Bergi Aug 12 '14 at 18:18
  • @AleksiAsikainen in Bluebird promises promises can have a form of context with `Promise.bind` - that feature is unavailable in Q. – Benjamin Gruenbaum Aug 12 '14 at 20:19
  • Note to self: `Deferred.notify()` also doesn't solve this, as it only notifies promises already attached in the chain. – Salieri Aug 13 '14 at 10:05

1 Answers1

0

Ended up writing my own implementation on top of Q, available here: https://github.com/franksrevenge/q/tree/v1-data-dispatch

Works as follows:

function doNothing {
    return true;
}

Q( true ).then( doNothing )
    .then( doNothing )
    .then( doNothing )
    .then( function() {
        return Q( true ).then( doNothing )
        .local(function(localData) {
            localData.myValue = 1234;
        }).then( doNothing );
   } )
   .then( function() {
        return Q( true ).then( doNothing ).local(function(localData) {
            console.log(localData.myValue);
        }).then( doNothing );
   } )
   .done();
Salieri
  • 782
  • 6
  • 17