1.如果函数a2执行依赖a1的返回值就会将a2函数的调用方法写入a1的回调函数中,如果是$ajax请求就需要卸载success中,如果依赖过多就会产生回调地狱。如下:
function a1(cb){ setTimeout(cb,1000); console.log('a1 finish'); } function a2(){ console.log('a2 finish'); } a1(a2);
2.可是使用when.js提供的方法解决回调地狱的麻烦
(1)在script标签中引入when.js文件
(2)
<script>
var f1 = function fn1(){
var deferred = when.defer();
var log1 = function(){
console.log('fn1 finish');
}
deferred.resolve(log1());
return deferred.promise;
}
var f2 = function fn2(){
var deferred = when.defer();
var log2 = function(){console.log('fn2 finish')};
setTimeout(function(){
deferred.resolve(log2());
},1000)
return deferred.promise;
}
var f3 = function fn3(){
var deferred = when.defer();
var log3 = function(){console.log('fn3 finish')};
setTimeout(function(){
deferred.resolve(log3());
deferred.notify(log3())
},2000);
return deferred.promise;
}
f1().then(f3).then(f2);
</script>
这样使用
var deferred = when.defer();
deferred.resolve(‘返回的数据’);
return deferred.promise;
就改成了链式调用。
“`