Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js: trouble with asynchronous code + js closures

Node.js: trouble with asynchronous code + js closures

Problem

I'm having trouble adapting to Node's single threaded + asynchronous nature, coupled with javascript's function closures.

Suppose I have something like:

function foo(bar) {
    someAsyncFunction(function callback(err) {
        // do stuff with 'bar'
    });
}

Please let me know if I'm missing something; but my understanding was that:

  • Due to closure, callback will have a reference to bar
  • However, if foo is called once with bar = 20, then again with bar = 42 before callback is invoked from the first call, then bar will be 42 in callback resulting from first call of foo. In other words:

    1. foo(20) #1
    2. someAsyncFunction(function callback() {}) #1
    3. foo(42) #2
    4. someAsyncFunction(function callback() {}) #2
    5. callback() #1 -------> uses bar=42
    6. callback() #2 -------> uses bar=42

Am I correct with this? (does it matter if bar is primitive or an object?). If so, what can I do to make sure callback uses the correct value of bar (ASIDE from passing bar all the way down & up the call stack)? Thank you for any help.

Problem courtesy of: Colin

Solution

That is not correct. Each invocation of foo creates a new bar, so each callback function will have access to a different bar.

If you want there to be only one bar, declare it outside of foo so that each invocation of foo shares the same bar:

var bar;
function foo(arg) {
    bar = arg;
    someAsyncFunction(function callback(err) {
        // do stuff with 'bar'
    });
}

Here, foo does not declare a new bar variable but rather sets the value of bar declared in a higher scope.

Solution courtesy of: apsillers

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js: trouble with asynchronous code + js closures

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×