将一组回调函数缩减为一个回调

Reduce array of callback functions to one callback

我想知道如何创建一个函数来调用数组中的所有函数而不显式创建一个函数。我说的是简单的 javascript(或者可能是一些下划线。js/lodash 助手,但我没有发现任何有用的东西)。

假设我们有一个接受回调的方法:

function doSmth(cb) {
  console.log('doing smth');
  cb();
}

现在我们有三个要调用的函数,但我们不想显式创建包装函数。

function write1() {
  console.log(1)
}

function write2() {
  console.log(2)
}

function write3() {
  console.log(3)
}

我们能否以某种方式将 [write1, write2, write3] 的数组简化为单个函数?我已经尝试将 Function.prototype.call 绑定到 Array.prototype.forEach 但我没有得到任何结果。

编辑:我忘了说我们不想修改 doSmth

没有第 3 方库,这很容易做到。您可以将 运行 作为 doSmth 函数中的回调的所有函数传递给另一个函数,首先 returns 循环遍历所有回调的函数:

function doSmth(cb) {
  console.log('doing smth');
  cb();
}

function write1() {
  console.log(1)
}

function write2() {
  console.log(2)
}

function write3() {
  console.log(3)
}

function mergeManyCallbacks() {
  var fns = Array.from(arguments);
  return function() {
    fns.forEach(fn => {
      fn()
    })
  }
}

// here is your call to doSmth
doSmth(mergeManyCallbacks(write1, write2, write3))

您可以使用 forEach 和一些辅助功能。

let invoke = (fn, ...args) => fn(...args);
arr.forEach(invoke);

// or for an array of the results
let results = arr.map(invoke);

// es5 translation of invoke
var invoke = function() {
  var fn = arguments[0];
  var args = [].slice.call(arguments, 1, arguments.length);
  return fn.apply(null, args);
};

let doIt = arr.forEach.bind(arr, invoke)
takesACallback(doIt);