callback() or return callback()

后端 未结 1 1238
一个人的身影
一个人的身影 2021-01-30 09:00

It\'s possible I don\'t understand Node\'s event loop well enough.

Say I have a function foo which contains an asynchronous function async_func

相关标签:
1条回答
  • 2021-01-30 09:52

    Actually, in your sample 2, //never executed will be execute every time. It's returning from the callback, not from the wrapping function.

    Sometimes the caller actually expects some return value and the behavior can change based on that. Another common reason to see a return callback() is just a clear way of short circuiting the function you're in. For example.

    function doSomething(callback) {
        something(function(err, data) {
            if(err) return callback(err);
            // Only run if no error
        });
        // Always run
    }
    

    Even though the return value isn't being used, it's using return to ensure that execution doesn't continue past the error conditional. You could just as easily write it this way which has the same effect.

    function doSomething(callback) {
        something(function(err, data) {
            if(err) {
                callback(err);
                return;
            }
            // Only run if no error 
        });
        // Always run
    }
    
    0 讨论(0)
提交回复
热议问题