javascript - 将回调的结果按顺序沿链向下传递到外部回调
问题描述
我试图将每个回调的结果按顺序传递到链中,并在外部调用中打印出来。如果您有任何想法,请告诉我我做错了什么以及如何解决它。
function first(cb) {
console.log('first()');
cb(null, 'one');
}
function second(cb) {
console.log('second()');
cb(null, 'two');
}
function third(cb) {
console.log('third()');
cb(null, 'three');
}
function last(cb) {
console.log('last()');
cb(null, 'lastCall');
}
let fns = [first, second, third, last];
function runCallbacksInSequence(fns, cb) {
const chainedFns = fns.reduceRight((acc, f) => () => f(acc), cb);
return chainedFns();
}
runCallbacksInSequence(fns, function(err, results) {
if (err) console.log('error');
console.log('outer call results: ' + results); // the results should equal to 'one','two', 'three', 'lastCall'
});
解决方案
我认为每次都无法保存回调结果。所以我尝试这样。
function first(cb) {
console.log('first()');
cb(null, 'one');
}
function second(cb) {
console.log('second()');
cb(null, 'two');
}
function third(cb) {
console.log('third()');
cb(null, 'three');
}
function last(cb) {
console.log('last()');
cb(null, 'lastCall');
}
let fns = [first, second, third, last];
function runCallbacksInSequence(fns, cb) {
let a = [];
fns.map(fn => fn((err, result) => a.push(result)))
cb(null, a);
}
runCallbacksInSequence(fns, function(err, results) {
if (err) console.log('error');
console.log('outer call results: ' + results); // the results should equal to 'one','two', 'three', 'lastCall'
});
推荐阅读
- windows - 如果不满足条件,如何退出巧克力安装?
- android - Android Xamarin 中的 Android 6.x 中的 ProgressBar.SetProgress 崩溃
- flutter - 在导航中使用带有 GlobalKeys 的小部件
- html - 春季启动 java.lang.NullPointerException: null
- php - 保存发送的firebase推送通知的正确方法是什么
- react-native - 无法连接到节点 infura
- ios - iOS:Firebase removeValue 似乎正在破坏数组数据?
- python - 预期的二维数组,改为标量数组
- postgresql - 如何正确扫描 pq 数组?
- c++ - 错误:程序停止执行 | 退出代码:255