Reputation: 97
I have trouble understanding the callback function with an parameter of err(error) I complete understand the callback function but find this specific topic a bit hard to understand because I don't know why and how a value or something is passed into the function without me calling the function and sending anything as parameters.so this is my first question.
My second question is :
I've been trying to use
object.insertMany([object1,object2],function(err) {
if (err) {
console.log(err);
}
So I noticed something about these kind of callback function such as
document.querySelector("#class").keypress(function(evt){
})
where I only use them when something triggers them, so is it true that I can only use those kind of functions such as function(err) or function(evt) in specific cases like those and I can not make a function with the err parameter such as this
function addition(x,y){
var result =x+y;
return result;
}
addition(1,2):
Upvotes: 1
Views: 487
Reputation: 4050
In your first couple of examples the insertMany
and keypress
functions are responsible for supplying the callback function with a parameter. (there isn't anything special about err
or errors, the functions would pass the error like you would any other parameter)
If want to write a function that supplies a parameter to a callback you definitely can!
function addition(x,y, callback){
var result =x+y;
var error = isNaN(result) ? 'Bad input!' : undefined;
callback(result, error);
}
addition(1, 2, function(res, err) {
console.log(res);
if(err) {
console.log(err);
}
});
addition('apple', 2, function(res, err) {
console.log(res);
if(err) {
console.log(err);
}
});
Upvotes: 1