简体   繁体   English

如何重写异步函数(node.js,和尚)

[英]How to rewrite asynchronous function (node.js, monk)

I'm trying to write an asynchronous function to give me a random document from a mongodb collection. 我正在尝试编写一个异步函数,以便给我一个来自mongodb集合的随机文档。

var getRandDoc = function(){
    var db = monk('localhost/data');
    var coll = db.get('coll');

    coll.count({}, function(err, count){
        if (err) console.log(err);
        else {
            coll.find({}, {limit:-1, skip:randomNum(0, count)}, function(err, out){
                if (err) console.log(err);
                else{
                    db.close();
                    return out[0]['name'];
                }
            });
        }
    });
}

In another file, I call this function with something like: 在另一个文件中,我用类似以下内容的名称来调用此函数:

console.log(test.getRandDoc());

And I get undefined undefined

What am I doing wrong and how do I fix it? 我在做什么错,我该如何解决?

It's the usual node callback confusion. 这是通常的节点回调混乱。 If you don't want to use promises then getRandDoc() needs to accept a callback and then call it with the results in the coll.find(...) method. 如果您不想使用Promise,则getRandDoc()需要接受一个回调,然后在coll.find(...)方法中将其与结果一起调用。 So something like this: 所以像这样:

var getRandDoc = function(cb){
    var db = monk('localhost/data');
    var coll = db.get('coll');

    coll.count({}, function(err, count){
        if (err) console.log(err);
        else {
            coll.find({}, {limit:-1, skip:randomNum(0, count)}, function(err, out){
                if (err) return cb(err)
                else{
                    db.close();
                    return cb(null, out[0]['name']);
                }
            });
        }
    });
}

You probably want to pass back that error too, so: 您可能也想传回该错误,因此:

test.getRandDoc(function(err, name){
});

A promise based version is going to look something like this: 基于promise的版本将如下所示:

var getRandDoc = function(){
    var db = monk('localhost/data');
    var coll = db.get('coll');
    var deferred = Q.defer();

    coll.count({}, function(err, count){
        if (err) deferred.reject(err);
        else {
            coll.find({}, {limit:-1, skip:randomNum(0, count)}, function(err, out){

                if (err) deferred.reject(err);
                else{
                    db.close();
                    deferred.resolve((out[0]['name']);
                }
            });
        }
    });

    return deferred.promise;
    }

But it's still not going to give you a straight forward variable assignment. 但这仍然不会给您直接的变量分配。 You'll wind up calling it something like this: 您最终会这样称呼它:

test.getRandDoc().then(function(res){}).fail(function(err){});

Welcome to node! 欢迎来到节点!

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

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