[英]Proper way to use Chrome local storage Get
I'm making a Chrome extension and am wondering what's the best way to use Chrome's asynchronous local storage get
. 我正在制作一个Chrome扩展程序,并且想知道使用Chrome的异步本地存储
get
的最佳方法是什么。 I want to use a number in the user's storage to return the right picture to be displayed. 我想使用用户存储中的数字来返回要显示的正确图片。 I have this function that sets the
window
's sheetURL
property to the correct URL of the picture: 我有将此函数设置
window
的sheetURL
属性为图片的正确URL:
var getCurSheet = function(){
chrome.storage.local.get('sheet', function(data){
$.isEmptyObject(data) ? sheetNum = 1 : sheetNum = data[0];
switch (sheetNum) {
case 1:
window.sheetURL = 'http://i.imgur.com/QlTafAU.png';
case 2:
window.sheetURL = 'http://i.imgur.com/jLGpcKz.png';
case 3:
window.sheetURL = 'http://i.imgur.com/2uAyumP.png';
default:
window.sheetURL = 'http://static.koalabeast.com/images/flair.png';
}
});
}
This gets called before I set an <img>
's source to be the link stored in window.sheetURL
: 在将
<img>
的源设置为存储在window.sheetURL
的链接之前,将调用此方法:
var flairs = document.createElement('img');
getCurSheet();
$(flairs).attr({
'src':window.sheetURL,
'id':'flairs'
});
Although this works, I get the feeling that this isn't the best solution to deal with asynchronous calls. 尽管这可行,但我感到这不是处理异步调用的最佳解决方案。 Is there a better way of handling this sort of thing?
有没有更好的方法来处理这种事情?
What you're looking for is called a Promise . 您要寻找的是一个Promise 。
Untested, but try this refactoring: 未经测试,但请尝试以下重构:
function getCurSheet () {
var sheetUrls = {
1: 'http://i.imgur.com/QlTafAU.png',
2: 'http://i.imgur.com/jLGpcKz.png',
3: 'http://i.imgur.com/2uAyumP.png'
};
var defaultSheetUrl = 'http://static.koalabeast.com/images/flair.png';
return new Promise(function (resolve, reject) {
chrome.storage.local.get('sheet', function(data) {
resolve(sheetUrls[data] || defaultSheetUrl);
});
});
}
getCurSheet().then(function (url) {
$('<img>').attr({
src: url,
id: 'flairs'
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.