Search code examples
javascriptgoogle-chromegoogle-chrome-extension

How to set chrome.alarms.getAll callback to a variable?


I am trying to use the chrome.alarms.getAll() method to get back the number of alarms there are into a variable I can use, but I am having trouble doing it because of the scope it's in. I'm not quite sure how to get it out, can anyone help? Code that's not working:

function query() {
  var count; 
  chrome.alarms.getAll(function(alarms) { count = alarms.length; }); 
  return count; 
}

var numAlarms = query(); //undefined

numAlarms returns undefined, even though I have 2 alarms and can see it when I use

chrome.alarms.getAll(function(alarms) { console.log(alarms) };

Solution

  • Use a callback function for query

    function query(callback) {
        var count; 
        chrome.alarms.getAll(function(alarms) { callback(alarms.length) }); 
    }
    
    query(function(count) {
        var numAlarms = count;
    });