影响回调函数中的变量 [英] Affect a variable in callback function

查看:78
本文介绍了影响回调函数中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这种问题非常常见,但是我无法做到。
我的代码如下所示。
某些 pubKeyProfiles 存储在chrome.storage中,我希望我的函数 getProfile 返回其中之一

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);
}

但是,由于我正在处理异步函数,配置文件仍为 null 不管我尝试什么。

But, as I am dealing with an asynchronous function, profile remains null whatever I try.

我的问题是:如何使函数 getProfile return profile ??

My question is : how can I make the function getProfile return profile ??

推荐答案

将回调函数传递给函数是一个更好的主意。

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
});

这篇关于影响回调函数中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆