我正在学习javascript回调或更高阶的功能。请帮助我理解以下功能中的错误。我试图调用多个函数作为回调函数。是不允许的?
我的代码是:
var firstFunction = function(item1){
console.log("calling firstFunction");
console.log(item1);
}
var secondFunction = function(item2, f1){
console.log("calling secondFunction");
f1(item2);
}
//secondFunction("first", firstFunction);
var thirdFunction = function(item3, f2,f1){
console.log("calling thirdFunction");
f2(item3);
}
thirdFunction("second", firstFunction, secondFunction);
答案 0 :(得分:0)
你所做的是正确的,但你必须将f1作为第三个函数的回调传递
var thirdFunction = function(item3, f2,f1){
console.log("calling thirdFunction");
f2(item3, f1);
}
答案 1 :(得分:0)
您的代码没问题,回调深度没有限制,但要注意stack overflow errors.
在您的代码中,您将在该脚本停止后执行第三个内部的firstFunction。我想你想要在thirdFunction中执行secondFunction,然后在第二个函数内执行:
check_library_exists
该代码将以描述的方式工作。
答案 2 :(得分:0)
请查看此脚本
var firstFunction = function(item1, f2) {
document.body.innerHTML += item1 + " | This is firstFunction <br/> ";
//console.log("calling firstFunction");
f2(item1, secondFunction);
}
var secondFunction = function(item2, f1) {
document.body.innerHTML += item2 + " | This is secondFunction <br/> ";
}
var thirdFunction = function(item3, f1, f2) {
document.body.innerHTML += item3 + " | This is thirdFunction <br/> ";
f1(item3, f2);
}
thirdFunction("chain started third function", firstFunction, secondFunction);
<html>
<body></body>
</html>