Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question