我正在检测一个值是否已经存储在localStorage中(如果localStorage存在),如果它不在数据库中(或者用户没有带有localStorage的浏览器),那么我运行一个AJAX GET请求。
if (Modernizr.localstorage) {
// there is storage
artist = localStorage.getItem('artist');
if (!artist) {
// but no cache
artist = fetchArtist();
localStorage.setItem('artist', artist)
}
} else {
// there's no storage
artist = fetchArtist();
}
function fetchArtist() {
var fetchedArtist;
var recentTracks;
$.get('script.php', [], function(data) {
recentTracks = data.recenttracks;
fetchedArtist = ((recentTracks !== undefined) ? recentTracks.track.artist['#text'] : 'Last.fm connection failed.');
}, 'json');
return fetchedArtist;
}
script.php只获取一个JSON字符串,jQuery将其转换为数据对象。我可以看到问题:因为$ .get是异步的,所以在函数可以分配我之后的值之前返回fetchedArtist变量,但是我想不出这样做的一种整洁方式(也许是全局变量,但是我真的不愿意。我可以在console.log中获取 $ .get中的fetchedArtist var 和我之后的值,但是fetchArtist函数总是返回undefined。
答案 0 :(得分:2)
您必须通过从fetchArtist()
函数中删除return语句来异步化您的工作流,因为$.get
请求的异步行为导致它无法满足您的需求。
尝试这样的事情:
if (Modernizr.localstorage) {
// there is storage
var artist = localStorage.getItem('artist');
if (!artist) {
// but no cache
fetchArtist();
} else {
doWhatYouNeedWithArtist( artist );
}
} else {
// there's no storage
fetchArtist();
}
function fetchArtist() {
var fetchedArtist;
var recentTracks;
$.get('script.php', [], function(data) {
recentTracks = data.recenttracks;
fetchedArtist = ((recentTracks !== undefined) ? recentTracks.track.artist['#text'] : 'Last.fm connection failed.');
if ( Modernizr.localstorage ) {
Modernizr.localstorage.setItem('artist', fetchedArtist);
}
// then do your stuff
doWhatYouNeedWithArtist( fetchedArtist );
}, 'json');
}
function doWhatYouNeedWithArtist( artists ) {
// do stuff
}
希望这有帮助!侨