为了处理这些情况,必须编写异步代码,而回调函数是处理这些情况的一种方法。所以从本质上上说,回调函数是异步的。, L& h. F, v9 v n! t g) Y 七、Javascript 回调地狱 ( n; }8 _) ^: R 当多个异步函数一个接一个地执行时,会产生回调地狱。它也被称为厄运金字塔。假设你要获取所有 Github 用户的列表。然后在用户中搜索 JavaScript 库的主要贡献者。再然后,你想要在用户中获取姓名为 John 的人员的详细信息。 6 w2 W. f9 t+ C' U1 E 为了在回调的帮助下实现这个功能,代码应该如下所示:7 u( N, P, ]5 N7 G
var async = require('async');
async.waterfall([
function(callback) {
/*
Here, the first argument value is null, it indicates that
the next function will be executed from the array of functions.
If the value was true or any string then final callback function
will be executed, other remaining functions in the array
will not be executed.
*/
callback(null, 'one', 'two');
},
function(param1, param2, callback) {
// param1 now equals 'one' and param2 now equals 'two'
callback(null, 'three');
},
function(param1, callback) {
// param1 now equals 'three'
callback(null, 'done');
}
], function (err, result) {
/*
This is the final callback function.
result now equals 'done'
*/
});
async.series() 6 `" {/ s" A7 y* h9 K 当你要运行一个函数然后在所有函数成功执行后需要获取结果时,它很有用。 async.waterfall() 和 async.series() 之间的主要区别在于, async.series() 不会将数据从一个函数传递到另一个函数。* W, U! P8 l! ?* v. c4 d
async.series([
function(callback) {
// do some stuff ...
callback(null, 'one');
},
function(callback) {
// do some more stuff ...
callback(null, 'two');
}
],
// optional callback
function(err, results) {
// results is now equal to ['one', 'two']
});
九、Javascript 回调与闭包5 S: P, I, E) w' H
闭包# e" \0 Q/ R7 _+ \9 G
用技术术语来说,闭包是捆绑在一起的函数的组合,引用了其周围的状态。简而言之,闭包允许从内部函数访问外部函数的作用域。要使用闭包,我们需要在一个函数内部定义另一个函数。然后,我们需要将其返回或传给另一个函数。 6 m) A- b( x! K回调 0 K: u6 p' G w 从概念上讲,回调类似于闭包。回调基本上是把一个函数作为另一个函数的用法。