2

I've created this function, however when it runs on the website it's designed for it is returning undefined. I did some quick Googling and found that because it's an asynchronous function, it completes and returns the data before the server can respond. I'm stumped however on how to convert it to a synchronous function.

Here is my code:

render_SC = function() {  
    var SC_url;
    $.get(Dubtrack.room.player.activeSong.url, function(f) {
        SC_url = f.data.songInfo.images.thumbnail.replace('large','original');
    });
    return SC_url;
};
console.log(render_SC());

Thanks in advance for all your responses. :)

  • 1
    The best thing to do is not convert it to a synchronous function (which you can't really do in any palatable way), but to design your API around the fact that it's asynchronous. That's the way things are done in JavaScript. – Pointy Nov 11 '15 at 22:19
  • 1
    You should rather be asking "How do I use asynchronous functions properly". There is a reason why these APIs are asynchronous. See http://stackoverflow.com/q/23667086/218196 and http://stackoverflow.com/q/14220321/218196 for how to do it right. – Felix Kling Nov 11 '15 at 22:20
  • in general, you shouldn't make synchronous calls on the main thread of browsers – Jaromanda X Nov 11 '15 at 22:21
  • Apologies for the duplicate thread. The other thread provided a solution that worked but that you all for your responses. :) – Lachlan Edwards Nov 11 '15 at 22:26
  • Even though this is a duplicate, I highly recommend *not* following that solution but learn how to work with asynchronous API's (e.g. from the links I provided). You will have to anyway, sooner or later. – Felix Kling Nov 11 '15 at 22:31
  • I'll have a look into it :) Thanks for the advice – Lachlan Edwards Nov 12 '15 at 02:02

0 Answers0