1

In nodejs or javascript code using the q library https://github.com/kriskowal/q will assigning the result of one function invoked by .then() to a function scope variable and using it in the next .then() invokation result in errors.

var q = require('q');

function example() {

    var result1;

    return q()
    .then(function() {
        result1 = 1;
        return 2;
    })
    .then(function(two) {
       return  result1 + two;
    });
}
Anil Kumar
  • 104
  • 6

2 Answers2

0

There is nothing wrong with assigning to higher level scoped variables as a means of accumulating results from chained promises. It is one method of doing so. Your example doesn't actually show any asynchronous operations, so it's not entirely clear exactly what you're trying to accomplish.

When assigning to a higher scope, you must make sure that no other code is trying to use that data until the promises have finished populating it.

You can see this post Collecting Data From Multiple Promises for a number of different ways to manage data across numerous related promises as assigning to a higher scoped variable is not the only possible way to do this.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • "When assigning to a higher scope, you must make sure that no other code is trying to use that data until the promises have finished populating it." This is eaxctly what I am after. For example, if the function is invoked multiple times will it lead to one invocation overwriting the intermediary values of another invocation? My understanding is that each invocation will have separate instances of the variable but is that correct? – Anil Kumar Mar 09 '16 at 08:29
  • @AnilKumar - Each invocation of your `example()` function will have a separate `result1` variable because it's a local variable in the function so there is no overwriting. If you moved `result1` to an even higher scope such as a global variable, then you could get overwriting. – jfriend00 Mar 09 '16 at 15:22
0

No, it will not error out... But your then() isn't resolving a Promise, so that might be problematic.

I'm not sure about Q (I use Bluebird), but it would be preferable if you use the spread operator that waits for the values of result1 and result2 to be resolved.

pyepye
  • 156
  • 1
  • 6