NodeJS Callback

原创转载请注明出处:http://agilestyle.iteye.com/blog/2352487

为什么NodeJS约定回调函数的第一个参数必须是错误对象err(如果没有错误,该参数就是null)?

因为执行分成两段,在这两段之间抛出的错误程序无法捕捉,只能当做参数传入第二段。

维基百科上的解释:

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

jQuery文档的解释:

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

先看一个简单地例子:

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:

鄙人对上述代码的诠释就是,比如你和你们同事一起去参加年会,舞台上看到一个颜好声甜身材曼妙的姑娘,于是乎,心中的欲望开始泛滥,想迫不及待去找个那个姑娘搭个讪认识一下,加个微信,留个联系方式什么的;但是呢,姑娘还在表演中,你又不立刻行动,只能先定个计划(等表演结束去搭讪她),这个计划就是callback,也就是简简单单的一个函数声明,具体的付诸实践呢,还能等表演结束之后,你去走套路进行搭讪,也就是函数的具体实现(每个人的搭讪方式不同,所以实现的方式也各有不同),最后非常可惜,你和你同事都搭讪失败,这个姑娘已经名花有主了。

再来看一个正常一点的例子,找点感觉

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 


 

猜你喜欢

转载自agilestyle.iteye.com/blog/2352487