Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript promises results scope [duplicate]

I need to chain some asynch actions. I'm trying to write Parse.com cloud code which uses express. (I think express is where the promises support originates). I see why promises are valuable, but am still unsure about a couple things. The first is how to collect the results of sequenced actions. The code below illustrates:

function doAsnychThingsInSequence(params) {
  return doThing0(params).then(function(resultOfThing0) {
    // thing1 depends on resultOfThing0
    doThing1(resultOfThing0);
  }).then(function(resultOfThing1) {
    // here is where I am confused.
    // thing2 depends on the results of thing0 and thing1
    doThing2(resultOfThing0 /* out of scope?? */, resultOfThing1);
  }, function(error) {
    // handle error
  });
}

After thing1 is done, I need the results of both actions. I think I can allocate a variable at the top of the function and assign it to the first result in the first callback, is that the right way? I guess, at the heart of my confusion is question two...

  return doThing0(params0).then(function(resultOfThing0) {
    doThing1(resultOfThing0);
    // what does return mean here?  does what I return here relate to the
    // parameters of the next function?
    return "foo";
  }).then(function(param) {
    // what is in param?  is it "foo"?
  }, function(error) {
});
like image 258
goodson Avatar asked Mar 29 '26 00:03

goodson


2 Answers

Promises can be imagined as a stream processing: one function gets input, does something with it and pass it to the next function in the chain.

So if you need to pass input (for the chain) parameters further you should include them into the output data so next one in the chain can use them:

function doThing1(params1) {
  ...
  return [params1, result1];
}

function doThing2(params1, params2) {
  ...
}

As you've mentioned you can use some variable outside doThing1 and doThing2 but it will make these functions statefull that may lead to side effects of various kinds. Not desired in general for async processing.

like image 96
c-smile Avatar answered Mar 31 '26 05:03

c-smile


The function supplied to then() must return a value, whether that value is the value to be used, or a promise for an upcoming value. Either way (per the promises spec) then() will return a new promise. That's the first issue I see with your code.

Next is that you have to store thing1 in a higher scope so that you can access it later. So something like this might be in order:

// example
var thing1;
getThing1()
.then(function(value){
  thing1 = value; // <-- store in higher scope
  return getThing2(); // <-- return
})
.then(function(value){
  thing2 = value;
  // now you have both thing1 and thing2 in scope
})
like image 20
greim Avatar answered Mar 31 '26 05:03

greim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!