2013-01-31 28 views
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模塊本身。

+0

[使用jQuery JavaScript的異步返回值/分配]的可能重複(http://stackoverflow.com/questions/7779697/javascript-asynchronous-return-value-assignment-with-jquery) – jbabey

+1

你不是已經在'stitchedBook =回覆;'?問題在於,您無法知道該值何時可用,因此只有在確定已設置該值的情況下才可以在回調中使用該值。 – bfavaretto

+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

但這看起來很糟糕,我從來沒有使用它! 您無法知道該值何時可用,因此只有在您確定已設置該值時纔可以使用該回調。

+0

謝謝。我可能不會使用它,但我只需知道。 -_- –