1

This works

chrome.storage.local.get('sizePref', function(items) { // Get size preferences from storage
  var sizePref2 = items.sizePref.tops; // Set size to a var
  console.log("You can get this " + sizePref2)
});

However, when I try to make it a function

function getSize(itemSize) {
  chrome.storage.local.get('sizePref', function(items) { // Get size preferences from storage
    var sizePref = items.sizePref.itemSize;
    return (sizePref);
  });
}
var mySize = getSize(tops);
console.log("This size that u are looking for is " + mySize)

it says "tops" is undefined.

1
  • 1
    @jfriend00 pointed out a serious issue in his answer - but I think another problem is that function getSize isn't returning anything - only the async function chrome.stroage.local.get does. Commented Oct 18, 2015 at 5:52

2 Answers 2

5

When the property name is in a variable, you use the bracket syntax. So, instead of this:

items.sizePref.itemSize

you use this:

items.sizePref[itemSize]

In addition, you cannot return a value synchronously from an async callback. That logic is just wrong. So, you can't make a function getSize() that will return the result. The result will not be available until some time LATER after getSize() already returns. You would have to either pass a callback into getSize() or have getSize() return a promise.

function getSize(itemSize) {
  return new Promise(function(resolve) {
      chrome.storage.local.get('sizePref', function(items) { // Get size preferences from storage
        resolve(items.sizePref[itemSize]);
  });
}

getSize("whatever").then(function(result) {
    // code that uses the result here
});
Sign up to request clarification or add additional context in comments.

Comments

0

If you are not familiar with promises (viz. unlikely) then you can use callbacks too. I personally think promises are a better way to solve your issue.

function getSize(itemSize, callback) {
  chrome.storage.local.get('sizePref', function(items) { 
    // Get size preferences from storage
    var sizePref = items.sizePref[itemSize]; //thanks @jfriend00
    callback (sizePref); //thanks at @Kevin Friedheim
  });
}
var mySize = getSize(tops, function (mySize) {
    console.log("This size that u are looking for is " + mySize)
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.