问题
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
??
回答1:
passing a callback to your function is a better idea.
var getProfile = function (keyPairId, callback) {
chrome.storage.local.get({ pubKeyProfiles : [] }, function (result) {
var pubKeyProfiles = result.pubKeyProfiles, profile;
profile = pubKeyProfiles.filter(function (pubKeyProfile) {
return pubKeyProfile.pubKey.keyId === keyPairId
})[0];
callback(profile);
});
};
getProfile(keyPairId, function (profile) {
//do something with profile here
});
来源:https://stackoverflow.com/questions/16720556/affect-a-variable-in-callback-function