如何通过模块中的变量正确存储共享数据

时间:2013-05-27 01:47:10

标签: node.js

我的应用程序在数据库中有一些共享数据,而不是为每个请求读取它们,我想只读出它们一次并将它们作为数组存储在模块中。但是,我不确定如何正确地做到这一点,任何帮助将不胜感激。谢谢!

var isStored = false;
var isStroing = false;
var allRecords = [];

function getSharedData(callback) {
   if (isStored) {
      callback(null, allRecords);
      return;
   }
   if (isStoring) {  // check to see if other request is doing the storing now
      // IT HAS TO WAIT AND GET THE RESULT LATER, BUT NOT SURE HOW TO DO IT
   }
   isStoring = true;

   ......
   // invoke a function retrieve the data from database;
   // populate allRecords array and set isStored to true
   .....
}

经过一番思考,这是我的解决方案。

var isStored = false;
var isStroing = false;
var allRecords = [];
var getSharedDataCallbacks = [];

function getSharedData(callback) {
   if (isStored) {
      callback();
      return;
   }

   getSharedDataCallbacks.push(callback);
   if (isStoring) {  
      return;
   }
   isStoring = true;

   // queryDatabase is not defined, basically, it retrieves
   // the data from database
   queryDatabase(function (error, result) {  
      var callbacks = getSharedDataCallbacks;
      getSharedDataCallbacks = [];
      isStroing = false;

      if (error) {
        callbacks.forEach(function (oneCallback) {
           oneCallback(error);
        }
        return;
      }
      allRecords = result; // assume result is an array 
      callbacks.forEach(function (oneCallback) {
          oneCallback();
      }
   });
}

function setSharedData(callback) {
    getSharedData.call(this, function (error) {
       if (error) {
          callback(error);
          return;
       }
       callback(null, allRecords);
    });
}

1 个答案:

答案 0 :(得分:1)

这样的事情可能有所帮助:

var loaded = false;
var loading = false;
var allRecords = [];

function getSharedData(callback) {
   if (loaded) {
      return callback(null, allRecords);
   }
   if (loading) {
      return (loading[loading.legnth] = callback);
   }

   loading = [callback];

   return loadData(afterLoad); //loadData is your function to load data.


   function afterLoad(err, data) {
       //process and assign to allRecords
       var i = 0
       , loadingLen = loading.length
       ;
       for(i; i < loadingLen; i++) {
         (function(cb, data) {
           cb(null, data);
         })(loading[i], allRecords);
       }

       loading.length = 0;
       loaded = true;
   }
}