1

So I've been looking at a bunch of questions on callbacks, and I can't seem to wrap my brain around getting my own code to work properly. I am trying to check URLs with the Soundcloud API to make sure they direct to working sounds.

function urlOK(url){
  SC.initialize({
    client_id: 'my_client_id'
  });
  SC.resolve(url).catch(function(error) {
    console.log(error.message);
    return false; // have tried callback here
  });
  // also want to return true if no errors are found
}

function checkAllInput(){
  if(urlOK(some_url){
    // do more logic
  }
}

With the code shown, urlOK of course blows past the resolve() call and "returns" false in the checkAllInput function. I have tried adding a callback function to urlOK in the spot indicated, and this correctly handled bad URL inputs. Good URL inputs did not "catch" though, and I am terribly confused as to how I should proceed.

I am happy to use jQuery, if it makes anything easier. :) I am also open to totally different approaches, and will answer questions as best as I can. Thank you for any help!

  • `urlOK` is asynchronous, [you cannot `return`](http://stackoverflow.com/q/14220321/1048572?how-to-return-the-response-from-an-asynchronous-call) any value from it. Return a deferred/promise for the boolean instead. – Bergi Mar 18 '16 at 22:30
  • Ahhhhh, ok I see, thank you very much! – WhudderButter Mar 18 '16 at 22:37

1 Answers1

0

What you are looking at here is a Promise. not a callback.

See: Promise - MDN

If you wanted to use a callback you would want to do something like this:

function urlOK(url, callback, error){
  SC.initialize({
    client_id: 'my_client_id'
  });

  SC.resolve(url).then(callback).catch(error);
}

function urlIsGood(){
  console.log('Url is good')
}

function urlIsBad(){
  console.log('Url is bad')
}

function checkAllInput(){
  urlOK(some_url, urlIsGood, urlIsBad)
}
xno
  • 1,225
  • 1
  • 13
  • 20