2

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

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);
    });
}
4

1 回答 1

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;
   }
}
于 2013-05-27T06:07:30.500 回答