MarksCode MarksCode - 4 months ago 23
Javascript Question

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
. 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:

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
:

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?

Answer

What you're looking for is called a 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'
   });
});