0

I have created a function which queries the Google Analytic API and get some data. It works fine. I used a console.log to confirm. But I need to get this data to a variable. Here's the function :

function getActiveUsers() {
    ...
    // Set data

      authClient.authorize(function(err, tokens) {
          if (err) {
              console.log(err);
              return;
          }

          analytics.data.realtime.get({
              auth: authClient,
              'ids': 'ga:ID',
              'metrics': 'rt:activeUsers'
          }, function(err, result) {
              console.log(err);
              return result; // I want this result
          });

      });
}

Now I wont the result into a variable like this :

result = getActiveUsers();

How can I do this? Please help.

THpubs
  • 7,804
  • 16
  • 68
  • 143
  • 5
    [This](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) should help. – Hunan Rostomyan Dec 05 '15 at 10:14
  • You can use something like that `function getActiveUsers() { return new Promise(function (resolve, reject) { authClient.authorize(function(err, tokens) { if (err) { reject(err); return; } analytics.data.realtime.get({...}, function(err, result) { if (err) { reject(err); } resolve(resolt); }); }); }); }` – Piotr Fryga Dec 05 '15 at 10:35
  • Then: `var promise = getActiveUsers(); promise .then(function(result) { // we can use result here }) .catch(function(err) { // handle error here });` – Piotr Fryga Dec 05 '15 at 10:36
  • Reopen question please, then I will pastie it in response – Piotr Fryga Dec 05 '15 at 10:37

0 Answers0