我试图通过这样做来消除“DOOM 回调金字塔”:
$$( //my function
function(next) { // <- next is the next function
setTimeout(next,1000); // simple async function
},
function(next){ // this function is the previous's function "next" argument
waitForSomethingAndReturnAValue(next, "I am a parameter!");
},
function(aValue){
console.log("My value is:" + aValue);
}
);
但是我已经摆弄了大约一个小时,我的代码不起作用,有什么帮助吗?这是我到目前为止得到的:
function $$(){
for (a in arguments){
arguments[a] = function(){
arguments[a](arguments[Math.max(-1, Math.min(a+1, arguments.length-1))]);
};
}
arguments[0]();
}
最佳答案
类似这样的东西:
function $$() {
if (arguments.length <= 0) return;
var args = Array.prototype.slice.call(arguments); // convert to array
arguments[0](function () { $$.apply(null, args.slice(1)); });
}
$$(function(next) { alert("one"); next() }, function (next) { alert("two"); next() });
关于javascript - JS 按顺序执行函数,同时传递下一个函数作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22732856/