How to use function argument as part of variable?

前端 未结 2 503
生来不讨喜
生来不讨喜 2021-01-25 00:22

This works

chrome.storage.local.get(\'sizePref\', function(items) { // Get size preferences from storage
  var sizePref2 = items.sizePref.tops; // Set size to a          


        
相关标签:
2条回答
  • 2021-01-25 00:28

    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
    });
    
    0 讨论(0)
  • 2021-01-25 00:37

    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)
    });
    
    0 讨论(0)
提交回复
热议问题