1

I am new to javascript callback functions. I've spent considerable time trying to get this to work, but keep falling short. I have the functions below. I simply want to call registrationFlow() and have it go into the if(found) condition, but getTrueFalse() always returns false. isRegistered inside getTrueFalse() is being set true (saw using an alert). Can someone help point out where my problem is? Very much appreciated!

function getTrueFalse() {
    var isRegistered = false;
    var registeredIds = ['APA','BBB'];
    chrome.storage.local.get("registeredId", function (result) {
        id = result["registeredId"];
        for(var i=0; i < registeredIds.length; i++) {
            if(registeredIds[i] === id) {        
                isRegistered = true;
            }
        }
    });  
    return isRegistered;
}

function registrationFlow() {
    chrome.storage.local.get("registered", function(result) {
        if (result["registered"]) {
            var found = getTrueFalse();
            if(found) {
                //do something
            }
        } else {      
            //do something else
        }
    });  
}
Terry
  • 989
  • 8
  • 29
obautista
  • 3,517
  • 13
  • 48
  • 83

2 Answers2

0

The function returns before the callback stores the value in isRegistered. The function chrome.storage.local.get is asynchronous.

You can solve this by creating your own callback function.

function getTrueFalse(callback) {
    // do stuff
    callback(true|false);
});

getTrueFalse(function(v) {
    console.log('return value ', v);
});

This is how asynchronous functions work, however, in your example there is no need for this as pointed out by @idrumgood.

Evers
  • 1,858
  • 1
  • 17
  • 18
0

Both functions are accessing the local storage, and I'm not sure why. Your registration flow should just be:

function registrationFlow() {
    var found = getTrueFalse();
    if(found) {
        //do something
    }
    else {      
      //do something else
    }  
}
idrumgood
  • 4,904
  • 19
  • 29