What is the correct way to add context to a callback used in a Model query? For example…
function doSomething(param) {
var magic = function(context, err, results) {
if(err) { console.log('fail'); }
else {
// do the magic with context and results
}
}
for( var i=0; i < 5; i++ ) {
var myObject = {'secret' : i};
MyModel.find({number:param[i]}, magic(myObject, err, results));
}
}
I’d like to loop through results for each query and have the context of myObject. The above solution does not work. ‘err’ and ‘results’ are not defined.
I normally do this with an anonymous function, but I can’t rely on the context inside the for loop.
errandresultsare undefined because you arer passing a variables callederrandresultstomagicwhich you never defined.MyModel.findcan’t do anything with the result frommagicbecause you don’t return anything from it, you should be returning a function that takeserrandresult.