NodeJS Callback

Please indicate the source for the original reprint: http://agilestyle.iteye.com/blog/2352487

 

Why does NodeJS stipulate that the first parameter of the callback function must be the error object err (if there is no error, the parameter is null)?

Because the execution is divided into two sections, the error program thrown between the two sections cannot be caught, and can only be passed to the second section as a parameter.

 

Explanation on Wikipedia:

In computer programming, a callback is a reference to a piece of executable code that is passed as an argument to other code.

 

Explanation from the jQuery documentation:

A callback is a function that is passed as an argument to another function and is executed after its parent function has completed. 

 

Let's look at a simple example:

function mainFunction(callback) {
	var someGirl = 'A girl who alreay has a boy friend';

	callback(someGirl);
}

mainFunction(function(a) {
	console.log("Hello: ");
	console.log(a);
});

mainFunction(function(b) {
	console.log("World: ");
	console.log(b);
});

Run

Note:

My interpretation of the above code is, for example, you go to the annual meeting with your colleagues, and you see a girl with a sweet face and a beautiful figure on the stage, so the desire in your heart begins to overflow, and you can't wait to find that girl. Get to know each other, add WeChat, leave a contact information or something; but, the girl is still performing, you don't act immediately, you can only make a plan (wait for the show to strike up a conversation with her), this plan is the callback , that is, a simple function declaration, put it into practice, you can also wait for the performance to end, you can go to the routine to strike up a conversation, that is, the specific implementation of the function (each person's approach to strike up a conversation is different, so the way of implementation It is also different). In the end, it is a pity that both you and your colleagues failed to strike up a conversation. This girl already has a famous flower.

 

Let's look at a normal example and get some feeling

var add = function(a, b) {
	return a + b;
};

var substract = function(a, b) {
	return a - b;
};

var multiply = function(a, b) {
	return a * b;
};

var divide = function(a, b) {
	return a / b;
};

var getParams = function(a, b) {
	console.log(a + ":" + b);
	return "200";
};

var calc = function(num1, num2, callback) {
	return callback(num1, num2);
};


console.log(calc(4, 2, add));
console.log(calc(4, 2, substract));
console.log(calc(4, 2, multiply));
console.log(calc(4, 2, divide));

console.log(calc(4, 2, getParams));

// anonymous function
console.log(calc(4, 2, function(a, b) {
	return a * b + a / b;
}));

Run 


 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327006374&siteId=291194637