0

I read somewhere that whenever a function gets called, the compiler puts all the visible variables on a stack, somewhat related to closures as well, now with the following code I'm not really sure if it'd work in a concurrent environment like node.js.

Product.prototype.list = function(body) {
    body.options = {
        hostname: endPoints.product,
        path: '/applications/' + body.entityType
        method: 'GET'
    };
    return remote.request(body)
        .then(function(result){
            body[body.entityType] = result;
            return body;
        });
};

Now if the following two function gets called concurrently using promises, will a closure occur? For instance

product.list({entityType: "coke"})
    .then(console.log); //will this have {coke: []} or {pepsi: []}

product.list({entityType: "pepsi"})
    .then(console.log); 
user2727195
  • 7,122
  • 17
  • 70
  • 118

1 Answers1

1

Yes a closure will be created by the anonymous function you pass to then. The variable which is being closed over is the body value being passed in to the outer list function.

Each time you call list - in the above example you've called it twice - you are adding some values to the body object and then instantiating a new closure and making that value available for it. The values that you're passing to each call of list are both object literals which means they're completely separate and you will be handing different values to the closure so there is no way the call involving 'coke' will ever have a connection to the call involving 'pepsi'.

Nicko
  • 631
  • 4
  • 7
  • for more information about time of closure creation, is that closure created when the function `list` is called or when `.then` is called? – user2727195 Jul 02 '16 at 22:59
  • @user2727195 - The closure is created when the `list()` function is called, as the free variable `body` is passed in, defined, and remember in that scope, which is also available in the `remote.request().then(...` function because it's lexical. – adeneo Jul 02 '16 at 23:08