首页 > 解决方案 > 将回调的结果按顺序沿链向下传递到外部回调

问题描述

我试图将每个回调的结果按顺序传递到链中,并在外部调用中打印出来。如果您有任何想法,请告诉我我做错了什么以及如何解决它。

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'
});

标签: 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) {
    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'
  });


推荐阅读