对象未返回 Javascript 中所需的对象

发布于 2025-01-03 06:14:01 字数 3720 浏览 0 评论 0原文

我不明白为什么 fetch 函数没有返回我想要的信息:

(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!');
            });
        }
    });
}());

我花了相当多的时间试图找出丢失的内容,但没有成功,也许有人会有更好的机会弄清楚出去。

I can't figure out why the fetch function is not returning the information I wish to have:

(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!');
            });
        }
    });
}());

I've spend quite some time trying to figure out what is missing, and didn't make it, maybe someone would have better odds of figuring out.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

揽清风入怀 2025-01-10 06:14:01

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

Promise 是处理异步代码的绝佳方式——它们可以在 jQuery、Dojo 以及其他库和工具包中使用。您的 fetch 方法可以返回一个 Promise,并且调用 fetch 方法的代码可以在返回的 Promise“已解决”时做出反应。 Dojo 的情况如下:

    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;
    },

然后,调用 fetch 的代码可能如下所示:

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

By the time the callback function from which you're trying to run return docs is being executed, the external fetch function has already returned -- as @SLaks suggested, welcome to the wonderful world of asynchronous programming.

Promises can be an excellent way for dealing with asynchronous code -- they're available in jQuery, Dojo, and other libraries and toolkits. Your fetch method could return a promise, and code that called the fetch method could react when the returned promise was "resolved". Here's what that looks like with Dojo:

    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;
    },

Then, code that called fetch might look like this:

myDB.fetch().then(function(docs) {
  // do whatever you need with the docs
});
月寒剑心 2025-01-10 06:14:01

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

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

外部函数实际上什么也不返回。因为函数 foo 只是将控制流返回到外部函数,而没有“inner”的信息。

如果您想返回某些内容,请将其移至外部函数的作用域。那会返回你想要的。

希望有帮助。

You can't do that, because in JS, function's expression return XXXX; means that the control flow returns to the outer function. For example:

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

The outer function really returns nothing. Because the function foo just returns the control flow to the outer function without the info of "inner".

If you want to return something, move it to the scope of outer function. That will return what you want.

Hope it helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文