代码之家  ›  专栏  ›  技术社区  ›  Bacroom App

同步执行nodejs

  •  0
  • Bacroom App  · 技术社区  · 7 年前

    我正在尝试编写一个函数,该函数接受mongodb集合名称作为参数,并返回集合的一个实例,以便它可以用于执行CRUD操作。但当我试图返回集合的实例时,它会返回 “未定义” 因为返回语句是在 MongoClient。连接 函数完成其执行。

    module.exports.dbConnection = function(collectionName)
    {
      var MongoClient = require('mongodb').MongoClient;
      var url = "mongodb://127.0.0.1/test";
      var collName;
      MongoClient.connect(url, function(err, db) 
      {
          var collName = db.collection(collectionName); 
          console.log(collName)
      });
      return collName;
    }
    

    我可以得到关于如何解决这个问题的帮助吗。 谢谢

    2 回复  |  直到 7 年前
        1
  •  0
  •   pizzarob    7 年前

    如果您正在使用至少7.10版本的Node,则可以使用异步函数和承诺来实现这一点。

    // You can return a promise and resolve the promise once connected
    module.exports.dbConnection = function dbConnection(collectionName) {
      const MongoClient = require('mongodb').MongoClient;
      const url = "mongodb://127.0.0.1/test";
    
      return new Promise((resolve, reject) => {
        MongoClient.connect(url, function (err, db) {
          if (err) {
            return reject(err);
          }
          resolve(db.collection(collectionName)); 
        });
      });
    }
    
    // You can then call the function within an async function (Node v7.10 and above)
    async function fnThatCallsDbConnection() {
      try {
          const collName = await dbConnection('someCollection');
      } catch(e){
        // do something with error
      }
    }
    

    let cachedDB;
    module.exports.dbConnection = function dbConnection(collectionName) {
      const MongoClient = require('mongodb').MongoClient;
      const url = "mongodb://127.0.0.1/test";
    
      return new Promise((resolve, reject) => {
        if (cachedDB) {
          resolve(cachedDB.collection(collectionName));
        } else {
          MongoClient.connect(url, function (err, db) {
            if (err) {
              return reject(err);
            }
            cachedDB = db;
            resolve(db.collection(collectionName)); 
          });
        }
      });
    }
    
        2
  •  0
  •   Hans Strausl    7 年前

    实现这一点的正确方法是使用回调。接受回调参数,然后在操作完成时将所需信息传递给该函数。

    module.exports.dbConnection = function(collectionName, cb)
    {
      var MongoClient = require('mongodb').MongoClient;
      var url = "mongodb://127.0.0.1/test";
      var collName;
      MongoClient.connect(url, function(err, db) 
      {
          var collName = db.collection(collectionName); 
          cb(collName); // invoke our callback
      });
    }
    

    dbConnection('collName', function (coll) {
        console.log(coll);
        // do something else with our collection
    })