Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a global variable from an asynchronous function

I'm stuck on this asynchronous function problem. I need to set a global variable with data which I get from a callback function. How can I do this?

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);
like image 891
user1330964 Avatar asked Dec 05 '25 18:12

user1330964


1 Answers

You may want to keep it simple, specially without shadowing your variables.

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

There is no reason to pass around soundId after all.

like image 92
Alexander Avatar answered Dec 07 '25 22:12

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!