node.js – 调用callback是否终止当前函数

我想调用一个可能遇到错误的util函数。 如果发生错误,则应终止processfunction。 正确抛出错误的唯一方法是callback函数。

我将通过返回来终止函数,但是由于我在util函数中,在util()调用之后, process函数将继续。

 function util(callback) { // do something synchronous if (err) { // doesn't terminate the process function // since we are in the util function return callback("something unexpected happened"); } } function process(callback) { util(callback); console.log("This should not be printed if an error occurs!"); } process(function (err) { if (err) { // this has to be executed in case of an error console.log(err); // terminate the process function somehow? } }); 

我build议你对你的代码做一些修改

 function util(callback) { // do something synchronous if (err) { // doesn't terminate the process function // since we are in the util function callback("something unexpected happened"); return false; } return true; } function process(callback) { if(!util(callback)) return; console.log("This should not be printed if an error occurs!"); } 

调用callback是否终止当前函数?

不,callback只是一个常规function。 这当然可能会抛出一个exception(虽然这是鄙视)。

我想调用一个可能遇到错误的util函数。 如果发生错误,则应终止过程function。

为此,您需要检查callback中发生了什么,并据此采取行动。 你可以使用process.exit来终止。

 function myProcess(callback) { util(function(err, result) { if (err) { callback(err); } else { console.log("This should not be printed if an error occurs!"); callback(null, result); } }); } myProcess(function (err) { if (err) { // this has to be executed in case of an error console.log(err); process.exit(1); } }); 

请注意,承诺可以简化这一点,因为它们区分成功和错误callback。 util将不得不返回一个承诺:

 function util() { return new Promise(function(resolve, reject) { // do something asynchronous if (err) reject("something unexpected happened"); else resolve(…); }); } function myProcess() { return util().then(function(res) { console.log("This should not be printed if an error occurs!"); return res; }); } myProcess().catch(function (err) { // this has to be executed in case of an error console.log(err); process.exit(1); // you might not even need this: throw err; // The node process will by default exit with an unhandled rejection }); 

这似乎是使用Promise的好时机,promise是Javascript强制同步函数的方式。 基本上你是这样设置的:

 var util = new Promise(function(resolve, reject) { /* do some stuff here */ if (someCondition) { resolve("With a message"); } else { reject("with a message"); } } function process() { util.then(function() { console.log("Won't call if there is an error"); }).catch(function() { console.log("There was an error, Bob"); }); } 

不,你会想要做这样的事情:

  function util(callback) { // do something synchronous if (err) { throw new Error('Something unexpected happened'); } callback(); // only execute callback if an error did not occur } function process(callback) { try{ util(callback); console.log("This should not be printed if an error occurs!"); } catch(error){ process(error); } } process(function (err) { if (err) { // this has to be executed in case of an error console.log(err); process.exit(1) } });