This kind of question is very frequent, but I could not make what I want.
My code look like this.
Some pubKeyProfiles
are stored in chrome.storage, and I want my function getProfile
to return one of them.
getProfile(keyPairId){
var profile = null;
chrome.storage.local.get({ pubKeyProfiles : [] }, function (result) {
var pubKeyProfiles = result.pubKeyProfiles;
for (var i = 0; i < pubKeyProfiles.length; ++i) {
if(pubKeyProfiles[i].pubKey.keyId === keyPairId){
profile = pubKeyProfiles[i];
}
}
});
console.log(profile);
}
After reading How to return value from an asynchronous callback function?, I tried the following code :
getProfile(keyPairId){
var profile = null;
function foo(fn){
chrome.storage.local.get({ pubKeyProfiles : [] }, function (result) {
var pubKeyProfiles = result.pubKeyProfiles;
for (var i = 0; i < pubKeyProfiles.length; ++i) {
if(pubKeyProfiles[i].pubKey.keyId === keyPairId){
profile = pubKeyProfiles[i];
fn(profile);
}
}
});
}
foo(function(profile){
return profile;
});
console.log(profile);
}
But, as I am dealing with an asynchronous function, profile remains null
whatever I try.
My question is : how can I make the function getProfile
return profile
??
passing a callback to your function is a better idea.