2

I have a doubt.. if I define variables before the .then() of a promise, I have them available inside the .then(), am I right? This is not true with callbacks, but it should using q promises.

To be sure of this, I am asking if the below code is correct, even in the case of multiple requests.

So the arg2 of the second .then() is always the right one, and it's not the arg2 of the last call to myapp().

function myapp()
{
    var arg1=1;
    var arg2=undefined;  // loaded async
    var arg3=undefined;  // loaded async

    call_promise(arg1)
          .then(function(data)
               {
                 arg2 = data;
               })
         .then(function()
              {
               arg3 = call_function(arg2);
               console.log(arg3);
              })
         .catch(function(err){});
}
DeLac
  • 1,068
  • 13
  • 43
  • 1
    Possible duplicate of [How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Joe Clay Mar 16 '16 at 11:00
  • It would work with non-promise callbacks just as well. – Bergi Mar 16 '16 at 11:04
  • @Joe mmh maybe not but thank you, it's an interesting lecture. It's always good read some theory explained in that easy way – DeLac Mar 16 '16 at 11:04
  • 2
    Just saying, [this is a horrible pattern](http://stackoverflow.com/a/28250700/1048572) :-) – Bergi Mar 16 '16 at 11:05
  • :P yes, I don't like it neither me, as suggested by @thefourtheye is much better, using return. thanks for the link with the explanation – DeLac Mar 16 '16 at 11:07

1 Answers1

3

Yes, that will work. No matter how many times the function is called, there will new variables created in the function. And because of the closure property, the functions passed to then handlers, will still be able to access arg2 and arg3.

But, the correct way to do this would be to, resolve the promises returned by then handlers, by returning the values, like this

function myapp() {
    var arg1 = 1;
    return call_promise(arg1)
        .then(function(data) {
            return data;
        }).then(function(arg2) {
            console.log(call_function(arg2));
        }).catch(function(err) {});
}
thefourtheye
  • 233,700
  • 52
  • 457
  • 497