2012-02-07 115 views
1

所需的对象我想不通为什么取功能没有返回的信息,我想有:对象不返回的Javascript

(function(){ 
    var root = this; 
    var Database = root.Database = {}; 

    var Db = require('mongodb').Db, 
    Connection = require('mongodb').Connection, 
    Server = require('mongodb').Server; 

    var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; 
    var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; 

    // Require Underscore, if we're on the server, and it's not already present. 
    var _ = root._; 
    if (!_ && (typeof require !== 'undefined')) _ = require('./underscore'); 



    Database.ActiveRecord = function(attributes, collection){ 
     this.collection = collection; 
     this.cid = _.uniqueId('c'); 
     attributes || (attributes = {}); 
     this.attributes = attributes; 
    }; 

    // Connecting to database and setting the connection as a shared variable among ActiveRecords 
    console.log("Connecting to " + host + ":" + port); 

    Database.ActiveRecord.prototype.db = new Db('node-mongo-eslip', new Server(host, port, {})); 

    _.extend(Database.ActiveRecord.prototype, { 

     initialize: function(){}, 

     // Returns `true` if the attribute contains a value that is not null 
     // or undefined. 
     has: function(attr) { 
      return this.attributes[attr] != null; 
     }, 

     // Sets attributes 
     set: function(key, value){ 
      var attrs, attr, val; 
      if(_.isObject(key) || key == null){ 
       throw Error("The key should not be an object or null"); 
      }else{ 
       attrs = {}; 
       attrs[key] = value; 
      } 

      if (!attrs) return this; 

      var now = this.attributes; 

      for(attr in attrs){ 
       val = attrs[attr]; 
       if(!_.isEqual(now[attr], val)) now[attr] = val; 
      } 
     }, 

     unset: function(key){ 
      return this.set(attr, null); 
     }, 

     toJSON: function() { 
      return _.clone(this.attributes); 
     }, 

     fetch: function(query, fields, options){ 
      var record = this; 
      record.db.open(function(err, db){ 
       if(!(record.collection||(typeof record.collection === 'string'))) throw Error('You should define a name attribute, which represents the collection of the Database'); 
       db.collection(record.collection, function(err, collection){ 
        console.log('Fetching...'); 
        collection.find(query, fields, options).toArray(function(err, docs) { 
         return docs; 
        }); 
       }); 
      }); 
     }, 

     save: function(){ 
      var record = this; 
      record.db.open(function(err, db){ 
       if(!(record.collection||(typeof record.collection === 'string'))) throw Error('You should define a name attribute, which represents the collection of the Database'); 
       db.collection(record.collection, function(err, collection){ 
        collection.insert(_.clone(record.attributes), {safe:true}, 
        function(err, objects) { 
         if (err) console.warn(err.message); 
         if (err && err.message.indexOf('E11000 ') !== -1) { 
          console.log('This id has already been inserted into the database'); 
         } 
        }); 
       }); 
       console.log('Saved!'); 
      }); 
     } 
    }); 
}()); 

我已经花了不少时间试图找出什么失踪,并没有成功,也许有人会有更好的计算出来的可能性。

+2

欢迎** **异步的奇妙世界!你不能那样做。 – SLaks 2012-02-07 01:27:53

+0

现在是有道理 – mabounassif 2012-02-07 01:45:00

回答

1

当你试图运行的回调函数return docs正在执行时,外部函数fetch已经返回 - 正如@SLaks所建议的,欢迎来到奇妙的异步编程世界。

Promise可以是处理异步代码的绝佳方式 - 它们可以在jQuery,Dojo和其他库和工具包中使用。您的fetch方法可能会返回一个承诺,并且在返回的承诺“解决”时,称为fetch方法的代码可能会作出反应。这里是什么样子与道场:

fetch: function(query, fields, options){ 
     var record = this, dfd = new dojo.Deferred; 

     record.db.open(function(err, db){ 
      if(!(record.collection||(typeof record.collection === 'string'))) throw Error('You should define a name attribute, which represents the collection of the Database'); 
      db.collection(record.collection, function(err, collection){ 
       console.log('Fetching...'); 
       collection.find(query, fields, options).toArray(function(err, docs) { 
        dfd.resolve(docs); 
       }); 
      }); 
     }); 

     return dfd.promise; 
    }, 

然后,那个叫取出码可能是这样的:

myDB.fetch().then(function(docs) { 
    // do whatever you need with the docs 
}); 
+0

我实际上修改了获取函数,以便它支持回调函数。现在它工作得很好。 http://howtonode.org/express-mongodb是我对有需要的人的参考。 – mabounassif 2012-02-07 04:01:59

1

你不能这样做,因为在JS中,函数的表达式return XXXX;意味着控制流返回到外部函数。例如:

(function(){ 
    function foo(){ 
     return "inner"; 
    } 
    foo(); 
})(); 

外层函数确实没有返回任何内容。由于功能foo只是将控制流程返回到外部函数,而没有“内部”信息。

如果您想返回某些内容,请将其移至外部函数的范围。这将返回你想要的。

希望它有帮助。