简体   繁体   English

在JavaScript中,使用forEach使用回调函数调用数组中的每个函数?

[英]in javascript, call each function in array with a callback using forEach?

An array of functions, [fn1,fn2,...] , each "returns" through a callback, passing an optional error. 函数数组[fn1,fn2,...] ,每个函数通过回调“返回”,并传递可选错误。 If an error is returned through the callback, then subsequent functions in the array should not be called. 如果通过回调返回错误,则不应调用数组中的后续函数。

// one example function
function fn1( callback ) {
   <process>
   if( error ) callback( errMsg );
   else callback();
   return;
}

// go through each function until fn returns error through callback
[fn1,fn2,fn3,...].forEach( function(fn){
  <how to do this?>
} );

This can be solved other ways , but nonetheless would love the syntactic dexterity to use approach. 这可以通过其他方法解决,但是仍然喜欢使用语法灵活的方法。

Can this be done? 能做到吗?


as per correct answer: 根据正确答案:

[fn1,fn2,fn3,...].every( function(fn) {
  var err;
  fn.call( this, function(ferr) { err = ferr; } );
  if( err ) {
     nonblockAlert( err );
     return false;
  }
  return true;
} );

seems this has room for simplification. 似乎有简化的空间。

for me, much better approach to solve this type of problem - it's flatter, the logic more accessible. 对我来说,解决这类问题的方法要好得多-它更扁平,逻辑更易于访问。

If I understand your question correctly and if you can use JavaScript 1.6 (eg this is for NodeJS), then you could use the every function. 如果我正确理解了您的问题,并且可以使用JavaScript 1.6(例如,这用于NodeJS),则可以使用every函数。

From MDN : MDN

every executes the provided callback function once for each element present in the array until it finds one where callback returns a false value. 每个函数都会对数组中存在的每个元素执行一次提供的回调函数,直到找到其中回调返回假值的元素为止。 If such an element is found, the every method immediately returns false. 如果找到了这样的元素,则every方法将立即返回false。 Otherwise, if callback returned a true value for all elements, every will return true. 否则,如果callback对于所有元素都返回true值,则每个元素都将返回true。

So, something like: 因此,类似:

[fn1, fn2, fn3, ...].every(function(fn) {
    // process
    if (error) return false;
    return true;
});

Again, this requires JavaScript 1.6 同样,这需要JavaScript 1.6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM