繁体   English   中英

mongodb nodejs在连接外部存储值

[英]mongodb nodejs store value outside connect

我需要一种在mongoDB connect调用之外存储值的方法:

read(object) {
    let result
    MongoClient.connect(this.url, function (err, db) {
        if (err!=null){
            result = err;
        } else {
            db.collection(object.collection).find(object.field).toArray(function(err, docs) {
                assert.equal(err, null);  
                db.close();       
                result = docs; 
            }); 
        }
    }); 
    return result
}

当我调用此方法(属于类的一部分)时,通常会在结果分配之前调用return。 示例: console.log(read(obj))返回未定义

想法是将值存储在变量中,返回可能要等到连接终止。

有什么办法解决这个问题?

没有承诺:

在find和err函数中调用return:

read(object) {
    let result
    MongoClient.connect(this.url, function (err, db) {
        if (err!=null){
            result = err;
            return result; //here
        } else {
            db.collection(object.collection).find(object.field).toArray(function(err, docs) {
                assert.equal(err, null);  
                db.close();       
                result = docs;
                return result;  // here
            }); 
        }
    });
}

或者将超时设置为返回时间有足够的时间来等待其他进程结束:

read(object) {
    let result
    MongoClient.connect(this.url, function (err, db) {
        if (err!=null){
            result = err;
        } else {
            db.collection(object.collection).find(object.field).toArray(function(err, docs) {
                assert.equal(err, null);  
                db.close();       
                result = docs; 
            }); 
        }
    }); 
    setTimeout(function(){ return result}, 3000);   // 3secs
}

使用Promise,您可以尝试以下操作:

function read(object) {
    let result
    return new Promise((resolve, reject) => {
        MongoClient.connect(this.url, function (err, db) {
            if (err!=null){
                reject(err);
            } else {
                db.collection(object.collection).find(object.field).toArray(function(err, docs) {
                    db.close();   
                    if (err) {
                        reject(err);
                    } else {
                        resolve(docs);                                        
                    }
                }); 
            }
        });
    });
}

// then you can call the function and use the result like this
read(obj).then(docs => {
    console.log(docs);
})
.catch(err => {
    // handle error
    console.log(err);
})

暂无
暂无

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

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