0

Take the following code snippet.

var exec = require('child_process').exec;

var extraInfo = {'test':1,'passing':'test'};

runWithData(extraInfo);

function runWithData(passedData)
{
    exec('/Users/test/Desktop/testcommand', function callback(error,stdout,stderr)
    {
        if (error)
        {
            console.log("ERROR",stderr);
        }
        else
        {
            console.log(stdout);
        }
    });
}

Within the callback of exec I want to be able to access the passedData. Is accessing passedData direct the correct way to do this and will this get overwritten if multiple function calls are being processed at the same time, or is there a way to attach the info into the callback function so it is tied to it?

2
  • This will help: developer.mozilla.org/en/docs/Web/JavaScript/Guide/Closures Commented Nov 8, 2014 at 6:41
  • 1
    You can just access 'passedData' directly. It's in a parent scope which is completely accessible to you in the callback. Each function call creates a new scope and thus creates a new set of data so multiple function calls do not mess it up. Commented Nov 8, 2014 at 6:51

1 Answer 1

1

From @jfriend00:

You can just access 'passedData' directly. It's in a parent scope which is completely accessible to you in the callback. Each function call creates a new scope and thus creates a new set of data so multiple function calls do not mess it up

See also: MDN Closures

[Note: Marked community wiki as this is mostly from others' comments, etc, for which I do not claim point credit. Feel free to edit and improve]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.