从异步函数返回变量

时间:2013-01-31 20:49:16

标签: javascript asynchronous

我有一个带有函数的模块,它为变量“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模块内部进行此操作。

1 个答案:

答案 0 :(得分: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处拥有它。

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