此函数获取响应并将响应写入localStorage
function getSomething() {
var d = $.Deferred();
var payload = ...
$.post(API, payload).done(function (data) {
// addData is a wrapper for localStorage write
addData(payload);
d.resolve();
}).fail(d.reject);
return $.when(d).done(function () {
console.log('API fetch OK');
}).promise();
}
然后在document.ready上执行
getSomething().done(function () {
// getData is a wrapper for localStorage read
var fs = $.grep(getData(), function (i) {
return i.cid == getID();
});
var fso = JSON.parse(fs[0].data);
$('.button-list').each(function (i, v) {
var buttonRow = '';
for (i = 0 ; i < fso.length ; i++) {
buttonRow += '<a id=' + getID() + '-' + fso[i].Content.Id + ' class=\'btn btn-default\'>' + fso[i].Form.Name + '</a>';
}
$(v).html(buttonRow);
});
所以这里的问题是我想在两者之间添加另一个函数,它在调用getSomething()之前检查localStorage中是否已经存在某些东西。这失败了因为getSomething已经完成了#39;在写入localStorage之前。经过一番摆弄后,我发现localStorage可以在getSomething完成后读取200ms。
我的问题 - 是否可以保证在getSomething进入&#39;之前已经写入了localStorage。状态吗
谢谢!
答案 0 :(得分:0)
以下是如何利用localStorage和Deferred对象创建getSomething的备用路径
var url =“https://jsonplaceholder.typicode.com/posts/1”;
function getSomething() {
var d = $.Deferred();
var storageResult = checkStorage();
debugger;
if (storageResult) {
console.log("Found in Storage");
return d.resolve(
storageResult
).promise();
} else {
return callAPI();
}
}
callAPI = function(){
var url = "https://jsonplaceholder.typicode.com/posts/1";
return $.ajax({
url : url
}).then(function(data, textStatus, promise){
debugger;
console.log("Made an API call");
addDataToStorage(data);
return promise;
}).fail(function() {
//fail handler
});
}
addDataToStorage = function(data) {
localStorage.setItem("tpiCode", data);
console.log("Added to Storage");
}
checkStorage = function() {
if (localStorage.getItem("tpiCode")) {
return localStorage.getItem("tpiCode");
}
}
var obj = getSomething();
debugger;
obj.done(function(data) {
$("result").html(JSON.stringify(data));
});