处理asynchronous节点错误的最佳方法

为了捕捉错误,我写了每个函数看起来不好的if-else块。 请build议一个更好的方法来处理asynchronous节点中的错误

async.waterfall([ function(callback){ fnOne.GetOne(req, res,function(err,result) { if(err){ console.error("Controller : fnOne",err); callback(err,null); } else{ var fnOne = result; callback(null, fnOne); } }) }, function(fnOne, callback){ fnTwo.two(fnOne,function(err,result) { if(err) { console.error(err); callback(err,null); } else{ callback(null, context); } }) } ], function (err, result) { if(err){ console.error("Controller waterfall Error" , err); res.send("Error in serving request."); } }); 

您可以将错误传递给asynchronous并在callback中捕获它

 async.waterfall([ function (callback) { fnOne.GetOne(req, res, callback); // err and result is passed in callback }, // as it's "function(err, result)" function (fnOne, callback) { // the same as the arguments for the fnTwo.two(fnOne, callback); // callback function } ], function (err, result) { if (err) { console.error("Error :", err); res.send("Error in serving request."); }else{ res.end("A-OK"); } }); 

你做的东西太多了

瀑布已经有一个内部的错误pipe理。

callback(err,[results]) – 一个可选的callback函数,一旦所有的函数完成运行。 这将传递最后一个任务callback的结果。

尝试这个

 async.waterfall([ function(callback){ fnOne.GetOne(req,res, callback) }, function(fnOne, callback){ fnTwo.two(fnOne,callback) { } ], function (err, result) { if(err){ console.error("Controller waterfall Error" , err); res.send("Error in serving request."); } }); 
 async.each(files, (file, callback) => { // Create a new blob in the bucket and upload the file data. const blob = bucket.file(file.file.originalname); const blobStream = blob.createWriteStream(); blobStream.on('error', (err) => { callback(err); }); blobStream.on('finish', () => { // The public URL can be used to directly access the file via HTTP. Storage.bucket(BUCKET_NAME) .file(blob.name) .move(body.email + '_' + file.dir + '.' + blob.name.split('.').pop()) .then((e) => { body[file.dir] = format(`https://storage.googleapis.com/${BUCKET_NAME}/${e[0].name}`) callback(); }) .catch(err => { console.error('ERROR: ', err); }); }); blobStream.end(file.file.buffer); }, (err) => { if (err) { console.error(err); return res.status(422).send({error: true, data: {message: "An error occured. Please fill all fields and try again"}}); } // save to db });