A
A
andrems2016-02-20 13:10:26
JavaScript
andrems, 2016-02-20 13:10:26

How to return the value of a variable from a callback function?

Good afternoon! It is not possible to return the value of a variable from a callback function that interacts with chrome.storage. The first alert returns undefined , and the second one fires with the desired value of the variable. What's wrong with the code?

var myData = { country: "Russia" };
chrome.storage.local.set(myData);
function getValue(callback) {
    chrome.storage.local.get(myData, function(response) {
      if (callback && typeof(callback) === "function") {
            callback(response);
       }
   });
}

var country = getValue(function(response) {

    alert(response.country);
    return response.country;

});
alert(country);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MNB, 2016-02-20
@andrems

async functions cannot return the value you want. That's why they are ASYNCHRONOUS. are executed in parallel with the main thread.

var country;
getValue(function(response) {
    country = response.country;

    // тут делаем что-то с кантри.
});

// тут country всегда будет undefined (как правило)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question