簡體   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