---
title: "NodeJS Callback"
author: "fairy_xzc"
date: "2017-01-11T16:50:18Z"
tags: []
categories: ["Web前端"]
slug: "nodejs-callback"
draft: false
lastmod: "2017-04-20T10:57:47Z"
id: 2352487
url: "https://agilestyle.iteye.com/blog/2352487"
---

**原创转载请注明出处：[http://agilestyle.iteye.com/blog/2352487](/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

![](http://dl2.iteye.com/upload/attachment/0122/5413/38d72d5a-3a1c-3f9c-a84a-707cfb98f142.png)

### 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 

![](http://dl2.iteye.com/upload/attachment/0122/5422/264cfc69-d06b-3e95-bd0f-6069627b42c0.png)