How to return the value in this function?

function getValue(variable, defaultvalue) { chrome.storage.sync.get({ [variable]: defaultvalue, }, function(items) { if (items[variable]) { return items[variable]; } }); } 

This is not possible, and if return items[variable] replaced with alert(items[variable]) then it is successfully displayed what is needed, and if with return it returns undefined .
It is necessary that when alert(getValue('test', 'var')) returns what I need, not undefined .

Reported as a duplicate by members Pavel Mayorov , pavel , Abyx , Grundy , user207618 Aug 11 '16 at 20:19 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • 2
    I advise you to get acquainted with such a relevant topic as asynchrony in Javascript. - Vladimir Morulus

1 answer 1

Since in this case the getValue function getValue nothing, the result of the execution

 getValue(variable, defaultvalue) 

will always be undefined .

Possible solutions:

  1. Forward callback - a function that will be called upon successful execution, for example

     function getValue(variable, defaultvalue, successCallback) { chrome.storage.sync.get({ [variable]: defaultvalue, }, function(items) { if (items[variable]) { successCallback(items[variable]);//вызываем callback если все хорошо } }); } 

    And call it as follows:

     getValue(variable, defaultvalue, function(items){//items внутри этой функции - будут нужным значением ... }) 
  2. You can use the Promise , like this:

     function getValue(variable, defaultvalue, successCallback) { return new Promise(function(resolve, reject){ chrome.storage.sync.get({ [variable]: defaultvalue, }, function(items) { if (items[variable]) { resolve(items[variable]);//говорим что все хорошо }else{ reject(/*тут можно указать причину почему все плохо*/); } }); }); } 

    And use so

     getValue(variable, defaultvalue).then(function success(items){//items внутри этой функции - будут нужным значением ... }); 
  • A question for connoisseurs - what is the difference between options 1 and 2? - Darth
  • one
    @Darth, nested callbacks look much worse than a call chain, especially if there are a lot of them - Grundy