获取变量中的回调的结果

时间:2018-10-20 16:33:19

标签: javascript mongodb variables callback electron

我面临着一个我无法解决的巨大问题。我想获取Mongodb函数collection.find()的结果,然后将结果放入一个变量中,该变量可以在另一个独立运行的函数中重用。 因为解释起来有些透彻,所以下面是代码:

client.connect(function (err) {
    assert.equal(null, err);
    const db = client.db(myDatabase);
    const collection = db.collection(myCollection);
    collection.find({}).toArray(function (err, docs) {
        //docs is the final result that I want to store in a variable
    });
});

$(myInput).change(function() {
    //using docs
})

'docs'是回调的结果,我不知道如何在变量中检索它。我试图将整个内容存储在一个变量中,我尝试了全局变量,但是没有任何效果,每次运行程序时我仍然得到undefined。 所以是的,我可以将函数运行到collection.find()

的回调中
client.connect(function (err) {
        assert.equal(null, err);
        const db = client.db(myDatabase);
        const collection = db.collection(myCollection);
        collection.find({}).toArray(function (err, docs) {
            $(myInput).change(function(docs) {
                //using docs
            })
        });
});

但是因为它是我经常运行的函数,所以它会经常调用Mongo,而这并不是性能的最佳选择,尤其是因为我的数据库正在另一台计算机上运行。

2 个答案:

答案 0 :(得分:1)

在全局范围内定义docs,并在find方法之后分配数据

let docs;

client.connect(async err => {
  assert.equal(null, err);
  const db = client.db(myDatabase);
  const collection = db.collection(myCollection);
  try {
    // docs is now a global variable containing all of the db collection
    docs = await collection.find({});
    myFunction();
  } catch (error) {
    // do something with the error
  }
});

function myFunction(){
  console.log("print docs", docs)
}

答案 1 :(得分:0)

Mongo也已经在异步中使用了Promise(假设v3 +)

Let doc=[];

client.connect(function (err) {
assert.equal(null, err);
const db = client.db(myDatabase);
Let collection=               db.collection(myCollection);
collection.find({})
.then(results=>{
  //modify data
  doc.push(results);
  myfunction();
 }

});

 function  myFunction(){
console.log(doc)
  }
相关问题