callback()或返回callback() [英] callback() or return callback()

查看:949
本文介绍了callback()或返回callback()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能不太了解Node的事件循环.

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

说我有一个函数foo,其中包含一个异步函数async_func.我有

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

//1
function foo(callback) {
       //stuff here
       async_func(function() {
            //do something
            callback();
       });
//this eventually get executed
}

//2
function foo(callback) {
       //stuff here
       async_func(function() {
            //do something
            return callback();
       });
//never executed
}

推荐答案

实际上,在示例2中,每次都会执行//never executed.它是从回调而不是包装函数返回的.

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

有时,调用者实际上期望一些返回值,并且行为可以基于此返回值而改变.看到return callback()的另一个常见原因只是使您所在的函数短路的一种清晰方法.例如.

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
}

即使未使用返回值,它也在使用return来确保执行不会在错误条件之后继续进行.您可以通过这种方式轻松编写具有相同效果的代码.

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
}

这篇关于callback()或返回callback()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆