瀑布函数没有重复 try/catch(使用异步瀑布)

No duplicate one try/catch by waterfall function (using async waterfall)

我正在使用异步瀑布,我有一个关于 try/catch 错误的问题。

我不想用一个全局 try/catch 来规避这种语法方法,并且不会通过函数重复 try/catch :

async.waterfall([
function (callback) {
  try {
     this.foo() // Ok
     this.bar() // Method bar doesn't exist so without try/catch node will crash
  } catch(ex) {
     //print err
  }
},
function (callback) {
  try {
     //Again & again
  } catch(ex) {
     //print err
  }
}
//... function() with try catch ...
], function(err, result) {
   //Do something
})

如果您寻求更健壮的错误处理系统;试试这个:

var async = require('async');


function callbackErrorHandler(fn, callback) {
  try {
    fn()
  } catch (err) {
    callback(err);
  }
}

async.waterfall([
  function(callback) {
   callbackErrorHandler(function() {
     throw new Error('error1');
   }, callback);
  },

  function(callback) {
    callbackErrorHandler(function() {
      throw new Error('error2');
    }, callback);
  }
],
//final
function(err, result) {
  console.log(err);
});


/**
 * Using Promises
 */
 var async = require('async');

//promises
var Promises = require('bluebird');

function callbackErrorHandler(fn) {
  return new Promises(function(resolve, reject) {
    try {
      resolve(fn()); //should return something
    } catch (err) {
      reject(err);
    }
  });
}

async.waterfall([
    function(callback) {
      callbackErrorHandler(function() {
        throw new Error('error1');
      })
      .error(callback)
    },

    function(callback) {
      callbackErrorHandler(function() {
        throw new Error('error2');
      })
      .error(callback)

    }
  ],
  //final
  function(err, result) {
    console.log(err);
  });

此脚本不再在最终回调和崩溃节点服务器中打印:

对此进行测试并尝试通过 testt() 重命名 test()

'use strict'

var async     = require('./lib/node_modules/async')

function test()
{
    console.log("hi !")
}
async.waterfall([
  function(callback){
    callback(null)
  },
  function(callback){
    test()
    callback(null, null)
  }], function (err, result) {
        if (err)
        {
            console.log("got an error !")
        }
        else
        {
            console.log("everyting is ok")
        }
  }
)