2

I'm unable to find answers to this, although it should be a relatively common issue. All other questions seem to relate to simply adding variables to an empty closure.

I have a callback which takes two arguments; err and docs, which I still need, but also want to add an additional argument of `data.

db.findOne().exec(function (err, docs) {
    // err is defined
    // docs is defined
});

I need to pass data along with it, so assumed I could do this:

db.findOne().exec(function (err, docs, data) {
    // err is defined
    // docs is defined
}(data));

This doesn't work. So, I tried the following:

db.findOne().exec(function (err, docs, data) {
    // err is null
    // docs is null
}(null, null, data));

This killed the original variables err and docs as well.

So, how would I go about doing this?

1
  • function (err, docs, data) { should return inner function as a handler of .exec Commented Apr 5, 2016 at 7:25

2 Answers 2

1

You could simply use the data variable inside the callback as long as this variable is defined in the outer scope (just before calling the db.findOne() method):

var data = ...
db.findOne().exec(function (err, docs) {
    // err is defined
    // docs is defined
    // data is defined
});
Sign up to request clarification or add additional context in comments.

Comments

0

You have to wrap your function within callback function .

if you have function like :

db.findOne().exec(function (err, docs) {
    // err is defined
    // docs is defined
});

you can use following function to pass additional parameters:

db.findOne().exec(function (err, docs) {
var data={a:'a'};
    yourFunction(err, docs, data);
});

function yourFunction(err, docs, data){
// access data here
}

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.