Mike
Mike

Reputation: 8877

How to pass ADDITIONAL arguments to an existing callback function

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?

Upvotes: 2

Views: 63

Answers (2)

Anupam Singh
Anupam Singh

Reputation: 1166

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
}

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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
});

Upvotes: 1

Related Questions