简体   繁体   English

node.js - 调用回调是否终止当前函数

[英]node.js - Does calling the callback terminate the current function

I want to call a util function that might encounter an error. 我想调用可能遇到错误的util函数。 In case of an error the process function should be terminated. 如果出现错误,应终止process功能。 The only way to throw an error properly is the callback function. 正确抛出错误的唯一方法是callback函数。

I would terminate the function by returning, but since I am in the util function, the process function will continue after the util() call. 我会通过返回来终止函数,但由于我在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?
    }
});

Does calling the callback terminate the current function? 调用回调是否会终止当前函数?

No, a callback is just a regular function. 不,回调只是一个常规功能。 It might of course throw an exception (although that is despised). 它当然可能会引发异常(尽管这是一种鄙视)。

I want to call a util function that might encounter an error. 我想调用可能遇到错误的util函数。 In case of an error the process function should be terminated. 如果出现错误,应终止过程功能。

For that, you need to check in the callback what did happen and act accordingly. 为此,您需要检查回调中发生了什么并采取相应措施。 You could use process.exit for termination. 您可以使用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);
    }
});

Notice that promises could simplify this a lot, as they distinguish between success and error callbacks. 请注意,promises可以简化这一过程,因为它们区分成功和错误回调。 util would have to return a promise for that: 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
});

No, you will want to do something like this: 不,你会想做这样的事情:

            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)
                }
            });

I suggest you make a few changes to your code 我建议你对代码进行一些更改

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!");
}

This seems like a good time to use a Promise, promises are Javascript's way of forcing a synchronous function. 这似乎是使用Promise的好时机,承诺是Javascript强制同步功能的方式。 Basically you set it up like this: 基本上你这样设置:

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");
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM