简体   繁体   English

为什么Mongoose的JavaScript在同一行中既有返回又有回调?

[英]Why does Mongoose's JavaScript have both a return and a callback in the same line?

I'm learning Mongoose and callbacks. 我正在学习猫鼬和回调。 I thought that callbacks are used in place of returns, so it's either callbacks or returns, but not both. 我以为使用回调代替了返回,所以要么是回调,要么是返回,但不能同时使用。 Then I stumbled upon this, where a return and cb are in the same line. 然后我偶然发现了这一点,其中returncb在同一行。

// define a schema
var animalSchema = new Schema({ name: String, type: String });

// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function (cb) {
  return this.model('Animal').find({ type: this.type }, cb);
}

var Animal = mongoose.model('Animal', animalSchema);
var dog = new Animal({ type: 'dog' });

dog.findSimilarTypes(function (err, dogs) {
  console.log(dogs); // woof
});

I Googled around and found this SO question with two answers both with callbacks, but one without a return, and one with . 我在Google周围搜索,发现了这样的问题,有两个答案都带有回调,但是一个没有返回值, 一个带有 Are they both correct? 他们俩都正确吗? If so, when should I put a return with a callback? 如果是这样, 我什么时候应该返回带有回调的内容?

Without a return: 没有退货:

animalSchema.statics.findByName = function (name, cb) {
    this.find({ name: new RegExp(name, 'i') }, cb);
}

With a return: 有回报:

animalSchema.methods.findSimilarTypes = function (cb) {
  return this.model('Animal').find({ type: this.type }, cb);
}

Typically in asynchronous programming techniques, it is a good practice to use a return statement along with callbacks at specific points. 通常,在异步编程技术中,最好在特定点使用return语句和回调。 For example, when the code has another callback further down. 例如,当代码在另一个回调中。 This prevents accidental execution of multiple callbacks within the same function. 这样可以防止意外执行同一函数中的多个回调。

Here is a very simple example: 这是一个非常简单的示例:

var failureCallback = function(err) {
    console.log("Failed");
    // do something with err
}

var successCallback = function(data) {
    console.log("Success");
    // do something with data        
}

var asyncFunction = function(failureCallback, successCallback) {
    getDataFromDb(err, data) {
        if(err) {
            failureCallback(err);
        }
    successCallback(data);
    }
}

In this case if there is an error, the first callback will definitely be called, but the second callback may also be called simultaneously. 在这种情况下,如果有错误,则肯定会调用第一个回调,但是也可以同时调用第二个回调。 So the console output might be: 因此,控制台输出可能是:

Failed
Success

To prevent this, you simply add a return statement to the failureCallback: 为了防止这种情况,您只需将return语句添加到failureCallback:

var asyncFunction = function(failureCallback, successCallback) {
    getDataFromDb(err, data) {
        if(err) {
            return failureCallback(err);
        }
    successCallback(data);
    }
}

Therefore, it is not the case that you can only use return or callback but not both. 因此,并非只能使用return或callback,而不能同时使用两者。 In fact in some case you must use them together. 实际上,在某些情况下,您必须一起使用它们。

All of this to say that, it is possible that in the case of your Mongoose examples, it may be a requirement by the function (although it does not seem so) but it may as well be a force of habit of the original author to use return along with callback. 所有这些都说明,在您的猫鼬示例中,这可能是功能的要求(尽管看起来并非如此),但这也可能是原作者习惯于使用return和回调。 Depending on the context, both are correct. 取决于上下文,两者都是正确的。 Using return could be either a necessary or unnecessary precaution in these use cases. 在这些用例中,使用return可能是必要的或不必要的预防措施。

With a return and callback on the same line you are "forcing" program to return from your function. 在同一行上有return和callback的情况下,您是“强制”程序从函数中返回。 If you just use callback, code afterwards would sometimes still get executed. 如果仅使用回调,则之后的代码有时仍会执行。

Example: 例:

someAsyncFunction(err, data) { 
    if(err){ 
       return callback(err)
     } 
     /* do some code with your data */ 
     callback()

That's an interesting difference. 那是一个有趣的差异。 Typically callbacks are used as a replacement for returns, but there is usually nothing technically wrong with having an extra return present - Mongoose would probably just ignore the returned data. 通常,回调被用作返回的替代品,但是通常存在多余的返回在技术上没有错-猫鼬可能只会忽略返回的数据。

My guess would be that the returns are present for consistency with other methods that don't use callbacks. 我的猜测是,存在返回值是为了与不使用回调的其他方法保持一致。 Like the following: 如下所示:

personSchema.virtual('name.full').get(function () {
  return this.name.first + ' ' + this.name.last;
});

Take this with a grain of salt - in my search of the Mongoose codebase I couldn't find any reason to include a return. 带着一点盐- 在我的Mongoose代码库中,我找不到任何包含退货的理由。 All in all, though, I'd have it anyway because it can't hurt and that's how mongoose documents it. 总而言之,我还是要拥有它,因为它不会造成伤害,这就是猫鼬记录它的方式。

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

相关问题 为什么返回的值应该与JavaScript中的return语句在同一行? - Why does the value returned should be on the same line as the return statement in JavaScript? 为什么javascript行必须在函数中才能工作? - Why does the javascript line have to be in a function to work? 为什么内容在 JavaScript 上返回相同的对象? - Why does the content return the same object on JavaScript? 为什么我的JavaScript实例返回相同的值? - Why does my JavaScript instances return the same? 在Angular控制器的回调中,为什么必须将参数命名为“ $ scope”? - In Angular controller's callback, why does parameter have to be named “$scope”? Mongoose如何保存回调功能? - How does Mongoose's save callback work? 为什么Java语言的Math.pow()与C语言中的相同,似乎返回一个四舍五入的值? - Why does Javascript's Math.pow() seem to return a rounded value compared to the same in C? 为什么Javascript的数组映射回调需要额外的参数 - Why does Javascript's array map callback require extra arguments JavaScript为什么getItem()有两种返回类型? - JavaScript Why does getItem() have two return types? 为什么此javascript函数针对同一查询返回两个不同的结果? - Why does this javascript function return two different results for the same query?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM