Affect a variable in callback function

陌路散爱 提交于 2019-12-11 06:44:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!