0

I'm trying to debug in Chrome's console and have created this small function for testing.

var hello = function(){
  var text = "Hello World";
  return text;
}; 

It works as I want it to, and when I call the function hello(); It returns the string "Hello World".

Now I'm not getting the same with this function using the Soundcloud API resolve endpoint.

 var idGetter = function(){ 
    SC.get('/resolve', { url: userURL }, function(user) {
      SC.get('/users/', function() {
        return (user.id);
      });
    });
  };

When I replace the return with console.log I get the value I'm looking for in the console so I know it's getting the data out, but when I use return I'm not able to call a value as I did in the "Hello World" function above.

Can add more code if it helps.

jermainecraig
  • 311
  • 4
  • 20

1 Answers1

0

This is typical Javascript behavior what is going on here is that the return is happening here....

var idGetter = function(){ 
 SC.get('/resolve', { url: userURL }, function(user) {
  SC.get('/users/', function() {
    return (user.id);
    // not here
  });
 });
 // Return happens here 
};

That is why the return is probably undefined. There are 2 ways people normally handle this, callback or promises.

1.) Callbacks

var idGetter = function(callback){ 
 SC.get('/resolve', { url: userURL }, function(user) {
  SC.get('/users/', function() {
    callback(user.id);
  });
 });
};
idGetter(function(id){
  return id;
})

2.) Promises

This is probably the route to take, if you are using a framework it may already include this, however, if not just include this library.

var idGetter = function(){
   var deferred = Q.defer();
   SC.get('/resolve', { url: userURL }, function(user) {
     SC.get('/users/', function() {
       deferred.resolve(user.id);
     });
   });
   return deferred.promise;
}

There are other options for handling this scenario but these are the 2 most common.

Update:

The other answer works with something like this but will not work on most mobile browsers yet (hopefully soon)

Jackie
  • 21,969
  • 32
  • 147
  • 289
  • Think i'll go with Promises, only i'm getting this error "deferred.promise is not a function". Added the library with a script tag, and replaced with your code. Doing some reading into it, and it seems it's already in jQuery? Would this mean I don't have to add the library? – jermainecraig May 07 '15 at 00:15
  • Sorry should be defer.promise not defer.promise() Some frameworks include promises, I would use this one https://api.jquery.com/deferred.promise/. The ECMA promise has a bit of a different syntax – Jackie May 07 '15 at 01:36