按顺序执行回调而不使用Promises [英] Executing callbacks in sequential order without using Promises
问题描述
我试图按顺序执行以下函数数组(避免使用callbackHell),以实现函数 runCallbacksInSequence
(我需要实现自己的函数,以了解回调的工作方式和避免使用Async.js)。这是我到目前为止所拥有的。我不太了解回调如何工作,这就是为什么我要进行此练习。如果您有任何想法,请让我知道我在做什么以及如何解决。
I am trying to execute following array (avoid callbackHell) of functions in a sequential order implementing function runCallbacksInSequence
(I need to implement my own function to understand how callbacks work and avoid using Async.js). Here is what I have so far. I do not quite understand how callbacks work that is why I am doing this exercise. If you have any ideas let me know what I am doing wrong and how I can fix it.
function first(cb) {
console.log('first()');
cb();
}
function second(cb) {
console.log('second()');
cb();
}
function third(cb) {
console.log('third()');
cb();
}
function last() {
console.log('last()');
}
let fns = [first, second, third, last];
function runCallbacksInSequence(fns, cb) {
return fns.reduceRight((acc, f) => f(acc), cb);
}
runCallbacksInSequence(fns, second);
callbackHell
// first(function() {
// third(function() {
// second(function() {
// last();
// });
// });
// });
UPD
const cache = {};
function runCallbacksInSequence(fns, cb) {
fns.reduce(
function(r, f) {
return function(k) {
return r(function() {
if (cache[f]) {
return;
// f(function(e, x) {
// e ? cb(e) : k(x);
// });
} else {
cache[f] = f;
return f(function(e, x) {
return e ? cb(e) : k(x);
});
}
});
};
},
function(k) {
return k();
}
)(function(r) {
return cb(null, r);
});
}
推荐答案
具有 .reduce
回调是一个高阶函数,该函数在被调用时将调用该回调链中的下一个函数。最后,您将具有一个功能链,该功能链将首先调用第一个函数,然后调用第二个函数,依此类推:
Have the .reduce
callback be a higher-order function, which, when called, calls the next function in the chain with the callback. At the end, you'll have a function chain that will start by calling the first function, then the second, etc:
function first(cb) {
console.log('first()');
cb();
}
function second(cb) {
console.log('second()');
cb();
}
function third(cb) {
console.log('third()');
cb();
}
function last() {
console.log('last()');
}
let fns = [first, second, third, last];
function runCallbacksInSequence(fns, cb) {
const chainedFns = fns.reduceRight((acc, f) => () => f(acc), cb);
return chainedFns();
}
runCallbacksInSequence(fns);
希望 runCallbacksInSequence
接受另一个回调在所有这些函数的末尾运行,然后:
If you wanted the runCallbacksInSequence
to accept another callback to run at the end of all of them, then:
function first(cb) {
console.log('first()');
cb();
}
function second(cb) {
console.log('second()');
cb();
}
function third(cb) {
console.log('third()');
cb();
}
function last(cb) {
console.log('last()');
cb();
}
let fns = [first, second, third, last];
function runCallbacksInSequence(fns, cb) {
const chainedFns = fns.reduceRight((acc, f) => () => f(acc), cb);
return chainedFns();
}
runCallbacksInSequence(fns, () => console.log('outer call'));
这篇关于按顺序执行回调而不使用Promises的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!