-3

I have a (asynchronous) function that gets the ID of a logged in user in Chrome. I'm trying to return the value of the ID with a callback but it keeps returning 'undefined'.

Before someone tries to mark this a duplicate, I used the code from here (and tried other places too): How to return value from an asynchronous callback function? But it didn't work:

function getGaia(callback) {
    chrome.identity.getProfileUserInfo(function(userInfo){
      var userId = userInfo.id;
      callback(userInfo.id);
    });
}

getGaia(function(id){
    return id;
});

var gaiaId = getGaia();

I get the following error:

'callback' is a not a function

What exactly am I doing wrong / what is the correct code?

Community
  • 1
  • 1

1 Answers1

2

That is because you are not providing a callback.

function doSomethingLater(callback) {
  setTimeout(callback, 1000);
}

console.log('This is before the callback');
doSomethingLater(function() {
  console.log('This is the callback')
});

So when you are calling var gaiaId = getGaia(); you are not passing in a callback function

[Edit] This is what your code would need to look like:

function getGaia(callback) {
    chrome.identity.getProfileUserInfo(function(userInfo){
      var userId = userInfo.id;

      // This will call the function that you pass in below 
      //and pass in userInfo.if as a parameter
      callback(userInfo.id); 
    });
}

var gaiaId = getGaia(function (id) {
    // id === userInfo.id from above
    // Do something with the id that you pass in
});

You can think of functions like variables in JavaScript,

So you can assign a function to a variable like this:

var foo = function () { ... }

This means that you can pass this into functions like normal variables. When you pass the function in as a parameter, you are assigning the function to the name that you specify in the parameters:

var foo = function () { ... }

function hasCallback(callback) {
    // The following two line do exactly the same thing:
    callback(); // Using the function that you passed in
    foo(); // Using the function directly
}

hasCallback(foo);

All I have done above is, instead of creating the variable foo I just created the function inline:

var foo = function () { ... }

function hasCallback(callback) {
    // The following two line do exactly the same thing:
    callback(); // Using the function that you passed in
    foo(); // Using the function directly
}

hasCallback(foo);

// Becomes: 

function hasCallback(callback) {
    callback(); // Using the function that you passed in
}

hasCallback(function () { ... });
Nicholas Robinson
  • 1,359
  • 1
  • 9
  • 20