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