开发者

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

An array of functions, [fn1,fn2开发者_JAVA技巧,...], each "returns" through a callback, passing an optional error. 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 (e.g. this is for NodeJS), then you could use the every function.

From 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. Otherwise, if callback returned a true value for all elements, every will return true.

So, something like:

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

Again, this requires JavaScript 1.6

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜