我想调用可能会遇到错误的util
函数。如果发生错误,应该终止process
函数。正确抛出错误的唯一方法是callback
函数。node.js - 调用回调是否终止当前函数
我会通过返回来终止函数,但由于我在util
函数中,所以函数将在util()
之后继续。
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?
}
});
我假定你的意思** A **同步在'util',否则你不会使用回调? – Bergi
@Bergi我使用回调,因为它传递给不受我控制的代码进行处理。 –
我想只有'process'应该调用回调函数,'util'应该是一个标准的同步函数。 – Bergi