我有一個函數,它爲變量「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模塊本身。
[使用jQuery JavaScript的異步返回值/分配]的可能重複(http://stackoverflow.com/questions/7779697/javascript-asynchronous-return-value-assignment-with-jquery) – jbabey
你不是已經在'stitchedBook =回覆;'?問題在於,您無法知道該值何時可用,因此只有在確定已設置該值的情況下才可以在回調中使用該值。 – bfavaretto
對不起。請參閱我的編輯。我可以得到價值。我只是想知道是否可以從模塊內部設置值。 –