【发布时间】:2014-10-07 00:48:48
【问题描述】:
我可以在将记录添加到存储后验证它是否存在,但是当我在另一个函数中并声明一个新变量以指向同一个数据库并存储并执行查询时,我收到以下错误消息。
存储:null 不存在。
我用来检索数据的方法已复制到我添加记录的位置,以确保它的语法正确并且在那里工作。但是当我在这个其他函数中时,它不再找到数据。
这里有一些代码:
我的目标是跟踪我缓存数据的时间,以便在数据过时时重新获取数据。 “updateCacheAge”方法似乎有效。记录对象填充了我期望的 JSON 对象。
updateCacheAge = function (dbName, cacheName) {
// updates the mashCacheAge. This helps track how old/stale a cache is.
var cacheJSON = {
id: cacheName,
updatedDate: new Date().getTime()
};
mashDB = new ydn.db.Storage(dbName);
mashDB.put({ name: 'mashCacheAge', keyPath: 'id' }, cacheJSON).done(function (key) {
mashDB.executeSql('SELECT * FROM mashCacheAge WHERE id = \'' + cacheName + '\'').then(function (record) {
$log.log('mashCacheAge record for: ' + cacheName);
$log.log(record);
});
});
$log.log(cacheName + ': mashCache was re-created.');
}
这是 isStale 函数。第一次通过我希望这可能会失败,因为缓存中没有任何内容。发生这种情况时,我知道要获取我的数据,然后更新 cacheAge 以防止我在缓存失效之前返回数据库。
我确信我的代码可以改进,但这是我解决问题的第一步。我遇到的问题是我刚刚保存到 mashCacheAge 存储的数据不存在,错误消息似乎表明存储本身不存在。
我在这里做了什么傻事吗?
isStale = function (dbName, cacheName, minutes) {
// db: is 'mashCache'
// store: No store is provided but might be added later to remove constaint 'mashCacheAge'
// subject: is the name of the cache being evaluated.
// minutes: is the number of minutes before the cache is considered stale.
var deferred = $q.defer();
var result = true;
// get milliseconds version of minutes.
var ageToleranceMilliseconds = (minutes * 60) * 1000;
var currentDateMilliseconds = new Date().getTime();
isStaleMashDB = new ydn.db.Storage(dbName);
try {
isStaleMashDB.executeSql('SELECT * FROM mashCacheAge WHERE id = \'' + cacheName + '\'').then(function (record) {
$log.log('mashCacheAge record for: ' + cacheName);
$log.log(record);
var durationMilliseconds = currentDateMilliseconds - record[0].updatedDate;
// Check if the data is stale.
if (durationMilliseconds > ageToleranceMilliseconds) {
result = true;
}
else { result = false; }
deferred.resolve(result);
});
}
catch (e) { deferred.resolve(true); }
return deferred.promise;
};
【问题讨论】:
-
一个建议:您应该为生产站点使用数据库模式。见dev.yathit.com/ydn-db/getting-started.html#h2-schema
标签: javascript caching indexeddb ydn-db