简体   繁体   English

当没有错误时,回调应该传递 null 还是 undefined?

[英]Should a callback be passed null or undefined when there is no error?

I'm hoping this is a simple question.我希望这是一个简单的问题。 Which is the accepted best practice for callbacks?哪个是回调的公认最佳实践?

Option 1:选项1:

function get (id, callback) {
    var topic = find(id);
    var err = new Error('Sorry, ' + id + ' is not a valid id.');
    err.status = 404;
    return (topic) ? callback(null, topic) : callback(err);
}

Option 2:选项 2:

function get (id, callback) {
    var topic = find(id);
    var err = new Error('Sorry, ' + id + ' is not a valid id.');
    err.status = 404;
    return (topic) ? callback(undefined, topic) : callback(err);
}

Side note, find() returns undefined , not null .旁注, find() 返回undefined ,而不是null

Thanks in advance.提前致谢。

I would do what the Node built-in API functions do.我会做 Node 内置 API 函数所做的事情。

A trivial experiment tells me that:一个微不足道的实验告诉我:

  • open passes null for err on success.成功时open通过null表示err

  • open passes null for the data parameter on failure. open在失败时为 data 参数传递null


A couple of other points:其他几点:

  1. Your code is always constructing an Error object, even if things worked.你的代码总是在构造一个Error对象,即使一切正常。 I wouldn't do that, it's pointless.我不会那样做,没有意义。

  2. Your code is returning the result of calling the callback.您的代码正在返回调用回调的结果。 That's unusual.这是不寻常的。

  3. Your code is calling the callback synchronously as far as I can tell.据我所知,您的代码正在同步调用回调。 (Eg, when calling get , the callback will occur before get returns.) Usually an async call is, you know, async. (例如,当调用get ,回调将在get返回之前发生。)通常,异步调用是异步调用。 If you're doing things synchronously, like openSync and such, put Sync on the name and return the value directly rather than calling a callback.如果您正在同步处理,例如openSync等,请将Sync放在名称上并直接返回值,而不是调用回调。

Passing null as an argument deactivate default parameter value mechanism.传递null作为参数停用默认参数值机制。 If callback function has default parameter values and you send null for empty parameter, callback function going to use null , not default value of parameter.如果回调函数具有默认参数值并且您为空参数发送null ,则回调函数将使用null ,而不是参数的默认值。

 function multiply(a=1, b=1){ return a*b; } console.log(multiply(undefined, 2)); console.log(multiply(null, 2));

The convention is null as seen here: https://docs.nodejitsu.com/articles/errors/what-are-the-error-conventions .约定为null如下所示: https : //docs.nodejitsu.com/articles/errors/what-are-the-error-conventions

As @TJ Crowder says in the comment, don't construct the error if it won't be sent back.正如@TJ Crowder 在评论中所说,如果错误不会被发回,请不要构建错误。

function get (id, callback) {
    var topic = find(id);

    if (topic) {
        return callback(null, topic);
    }

    var err = new Error('Sorry, ' + id + ' is not a valid id.');
    err.status = 404;

    return callback(err);
}

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

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