【问题标题】:Significance and Reason for using a callback?使用回调的意义和原因?
【发布时间】:2014-05-27 12:25:36
【问题描述】:

异步和回调仍然是我难以理解的概念。我一直在阅读并试图理解使用它们来获得更多熟悉的代码。我不明白为什么这段 sn-p 代码使用回调而不是仅仅传入一个值(而不是一个匿名函数,其参数作为要评估的值)。

Shorten.prototype.Lookup = function (url, callback){
    var mongoose = this.app.locals.settings.mongoose;
    var Cursor = mongoose.model('urls');
    Cursor.find({"linkFinal": url}, function(err, docs){
        if (err === null){
            if (typeof(callback) === "function"){
                if (docs[0] !== undefined){
                    callback(docs[0]);
                    return docs[0];
                }else{
                    callback(false);
                    return false;
                }
            }
        }else{
            console.log(err);
        }
    });
};

这是一个用例中的代码函数:

shorten.LookUp(url, function(urlCheck){
           if (urlCheck === false){
                //Add to db
                // another function that uses a callback as second parameter
                shorten.addLink(shortenURL, shortURL){
                    small.shortenedURL = "http://" + domain + "/" + shortURL.link;
                    small.shortenError = false;
                    small.alreadyShortened = false;
                    res.json(small);
                });
            }else{

                small.shortenedURL = "http://" + domain + "/" + urlCheck.link;
                small.shortenError = false;
                small.alreadyShortened = true;
                res.json(small);
            }
        });

我对为什么在这种情况下使用回调函数的唯一直觉是,当对数据库进行查询时(在这种情况下 mongodb 使用 Mongoose api),该函数仅在数据可用时运行(即情况:

    // after the result of the query is ran, the result is passed to the function in 
    // the docs parameter.                              
    Cursor.find({"linkFinal": url}, function(err, docs){

这是我想出为什么要传递回调而不仅仅是一个值的主要原因。我仍然不能 100% 确定为什么这不起作用:

Shorten.prototype.LLookUp = function (url, value){
    var mongoose = this.app.locals.settings.mongoose;
    var Cursor = mongoose.model('urls');
    Cursor.find({"linkFinal": url}, function(err, docs){
        if (err === null){
                if (docs[0] !== undefined){
                    return docs[0];
                }else{
                    value = false;
                    return false;
                }
            }
        }else{
            console.log(err);
        }
    });
};

我在这种情况下所做的只是删除匿名函数并传递该函数的参数。

  • 为什么在第一个代码 sn-p 中首选回调而不是仅仅 传递参数?
  • 第三个代码 sn-p 是否可行?如果不是,为什么?

谢谢!

【问题讨论】:

    标签: javascript node.js asynchronous callback


    【解决方案1】:

    return 语句在回调函数内部,不是LLookUp 函数。因此它们将返回给调用回调的任何人(猫鼬库),但是猫鼬库不会对回调返回的值做任何事情,因此返回任何值都是无用的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      • 2015-11-29
      • 2011-10-21
      相关资源
      最近更新 更多