0

I want to get the klout score using a screen name (twitter).

I did this. I know it doesn't work like that, but I don't know how it should work.

function get_klout(screenName){
  klout.getKloutIdentity(screenName, function(error, klout_user) {
    klout.getUserScore(klout_user.id, function(error, klout_response) {
       return Math.round(klout_response.score);
    });
  });
}

I want my function to return this number Math.round(klout_response.score);

Aaron Aben Danan
  • 322
  • 1
  • 3
  • 14

2 Answers2

0

Because this is an asynchronous function you cannot use return, in order to return result from asynchronous code pass to your function callback and return the result on the callback. you should handle errors in your callbacks.

  function get_klout(screenName, callback){
  klout.getKloutIdentity(screenName, function(error, klout_user) {
    if (err){
      callback(error);
      return
    }
    klout.getUserScore(klout_user.id, function(error, klout_response) {
      if (err){
        callback(error);
        return
      }
      callback(null, klout_response.score);
    });
  });
}

get_klout(screenName, function(err, res){
  if (err){
    console.log(err);
    return
  }
  console.log(res);
});
Lena Kaplan
  • 756
  • 4
  • 13
0
function get_klout(screenName) {

  klout.getKloutIdentity(screenName, function(error, klout_user) {

    klout.getUserScore(klout_user.id, function(error, klout_response) {

       return Math.round(klout_response.score);
    });
  });
}

Your function is async, so you can't just assign what it returns to a variable because you will just assign undefined: var result = get_klout('foo'); // undefined

what you can do is:

  1. using async functions in node 8+
  2. using Promises
  3. using callbacks:
function get_klout(screenName, done) {

  klout.getKloutIdentity(screenName, function(error, klout_user) {

    klout.getUserScore(klout_user.id, function(error, klout_response) {

        done(Math.round(klout_response.score));
    });
  });
}

get_klout('foo', function(response) {
  console.log(response);
});

just a note: In node is a common pattern implementing the error first callback and you should have a look on it because it's the traditional and more used way to handle errors: http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/

Hitmands
  • 13,491
  • 4
  • 34
  • 69