0

我有一个带有函数的模块,它为变量“stitcheBook”生成变量的值。我可以通过回调查看和使用这个值。

但是,我希望将此值作为模块属性提供给我。我怎样才能做到这一点?

注意:我希望 _BookStitcher.stitchAllStories 函数的输出进入 _BookStitcher.stitchedBook 属性。

module.exports = _BookStitcher = (function() {

var db = require('../modules/db');
var stitchedBook = {};

var stitchAllStories = function(callback) {


    db.dbConnection.smembers("storyIdSet", function (err, reply) {
        if (err) throw err;
        else {
            var storyList = reply;
            console.log(storyList);
            // start a separate multi command queue
            multi = db.dbConnection.multi();
            for (var i=0; i<storyList.length; i++) {
                multi.hgetall('story/' + String(storyList[i]) + '/properties');
            };
            // drains multi queue and runs atomically
            multi.exec(function (err, replies) {
                stitchedBook = replies;
                // console.log(stitchedBook);
                callback(stitchedBook);
            });
        };
    });


};


return {
    stitchedBook : stitchedBook,
    stitchAllStories: stitchAllStories

}

})();

编辑:补充:我知道我实际上可以通过做这样的事情从外部设置值;

_BookStitcher.stitchAllStories(function (reply) {
        console.log("Book has been stitched!\n\n")
        console.log("the Book is;\n");
        console.log(reply);
        _BookStitcher.stitchedBook = reply;
        console.log("-------------------------------------------------------------------------\n\n\n");
        console.log(_BookStitcher.stitchedBook);

});

我想知道是否有一种方法可以从 _BookStitcher 模块本身内部进行。

4

1 回答 1

1

可以利用对象引用在 JavaScript 中的工作方式,并将其分配给属性:

module.exports = _BookStitcher = (function() {

    var db = require('../modules/db');

    // CHANGE HERE
    var stitched = { book: null };

    var stitchAllStories = function(callback) {
        db.dbConnection.smembers("storyIdSet", function (err, reply) {
            if (err) throw err;
            else {
                var storyList = reply;
                console.log(storyList);
                // start a separate multi command queue
                multi = db.dbConnection.multi();
                for (var i=0; i<storyList.length; i++) {
                    multi.hgetall('story/' + String(storyList[i]) + '/properties');
                };
                // drains multi queue and runs atomically
                multi.exec(function (err, replies) {
                    // CHANGE HERE
                    stitched.book = replies;
                    // console.log(stitchedBook);
                    callback(replies);
                });
            };
        });
    };

    return {
        stitched : stitched,
        stitchAllStories: stitchAllStories
    };

}());

因此,与其把它放在里面_BookStitcher.stitchedBook,不如把它放在_BookStitcher.stitched.book.

但这看起来很糟糕,我永远不会使用它!您无法知道该值何时可用,只有在您确定已设置时,才能从回调中使用它是安全的。

于 2013-01-31T20:59:10.163 回答