asynchronous - 如何从异步函数设置全局变量

标签 asynchronous google-chrome-extension callback

我被这个异步函数问题困住了。我需要使用从回调函数中获取的数据设置一个全局变量。我该怎么做?

var soundId;

soundcheck(soundId, function (num){getSound(soundId, num)});
//callback 
function getSound (soundId, result) {
var res = result;
if (!soundId) {
    soundId = res;
    }
    console.log(soundId);
};


function soundcheck(soundId, callback) {
    var lpid = $("a#entered_user_link").attr('href').substring(6);
        chrome.extension.sendMessage({lpid: lpid}, function(response) {
        if (response.resp) {
            check = response.resp;
            callback(check);
        }
    });
};

// i need to put response in this variable to use it in future
console.log(soundId);

最佳答案

您可能希望保持简单,特别是不要隐藏变量。

var soundId;

soundCheck(function(result) {
  if(result) { 
    soundId = result;
  };
});

var soundCheck = function(callback) {
  var lpid = $("a#entered_user_link").attr('href').substring(6);
  chrome.extension.sendMessage({lpid: lpid}, function(response) {
    callback(response.resp);
  });
};

毕竟没有理由传递 soundId

关于asynchronous - 如何从异步函数设置全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12998003/

相关文章:

asynchronous - 异步api调用后如何使用vuex getter

jquery - 如何在 '.append()'循环内同步 'for'和ajax查询

javascript - Chrome 扩展 : Extension context invalidated when getting URL

javascript - 从 chrome 扩展监控 history.pushstate

ios - 从主视图 Controller iOS 访问已解析的 JSON 数据

javascript - 在事件监听器中触发函数之前等待异步调用完成

python - 服务器/客户端应用程序和 JSONDecodeError : Unterminated string python

javascript - 文件系统 API - 保存目录在哪里?

javascript - 为什么这个回调会触发两次?

java - 无法通过回调方法更新textview