callback
A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.
就是说把一个函数当做另一个函数的参数传递进去,当另一个函数执行完毕时在该函数体内执行被传递进去的函数。
function doSth(cbOk) {
console.log("has do sth !");
console.log("begin to do cbOk fun");
cbOk();
};
doSth(sthFinish);
function sthFinish() {
console.log("success");
}
此处在调用doSth函数时,将sthFinish函数当做参数传给doSth,当doSth函数体内某处需要执行sthFinish函数时,调用传递进来的函数。
参数
被传进函数体内当做回调的函数同样可以携带参数,在实际被调用的地方传参。
function doSth(cbOk) {
console.log("has do sth !");
console.log("begin to do cbOk fun");
cbOk("excellent");
};
doSth(sthFinish);
function sthFinish(parameter) {
console.log("success", "所传参数:", parameter);
}
如上,需要在回调函数sthFinish调用时传一些参数以方便做其他的事情。
回调地狱
回调地狱是一种需要尽量被规避的写法,回调的目的本身是为了实现同步等待完成执行下一步操作,使用过多可能会造成回调地狱现象,嵌套层级过多造成代码理解生涩、难以维护。可以使用es6的promise新特性来完成链式同步任务调用(回调函数与promise本身是为解决程序异步可能导致的问题,即完成再进行下一轮任务,不完成不进行)。
function doSth(parameter, cbOk) {
console.log("has do sth !", "begin to do cbOk fun");
console.log("parameter", parameter);
cbOk();
};
doSth("first", function () {
doSth("second", function () {
doSth("third", function () {
doSth("fourth", function () {
console.log("还没完");
})
})
});
});
递归
递归就是在函数体内调用本函数,可以在一些特殊场景或者遍历(每一轮彻底完成后再进行下一轮)上使用。使用递归需要注意的是留意递归出口,避免死循环。
let demoArray = [12, "test", "45", 56, "ry", 76, 87, "sc", 234, 576, ];
let itIndex = 0;
function ergodic(param, itIndex) {
let item = param.shift();
itIndex++;
console.log("第" + itIndex + "条:", item);
if (param.length > 0) {
ergodic(param, itIndex);
} else {
return;
}
};
ergodic(demoArray, itIndex);
实现递归与回调
就是在递归结束后进行回调,开始下一步任务。
let demoArray = [12, "test", "45", 56, "ry", 76, 87, "sc", 234, 576, ];
let itIndex = 0;
function ergodic(param, itIndex, cbOk) {
let item = param.shift();
itIndex++;
console.log("第" + itIndex + "条:", item);
if (param.length > 0) {
ergodic(param, itIndex, cbOk);
} else {
console.log("递归结束!");
cbOk();
}
};
function sthFinish() {
console.log("完成,准备进行下一轮任务!");
}
ergodic(demoArray, itIndex, sthFinish);