Function $ .getJSON returns undefined

3

I'm having problems with a system that downloads the photo of 10 artists from a TOP 10. Here is the function:

function baixarCapa(capa) {
   $.getJSON("https://ajax.googleapis.com/ajax/services/search/images?callback=?", {
       q: '"' + capa + '"',
       v: '1.0'
   }, function(data) {
       return data.responseData.results[0].url;
   });
}

And below:

showTopMusicas: function(){
    this.ajax('callCustomApi', ['getTop'], function(dados) {
        if (!dados || !dados.length) {
            return;
        }

        var html = '';
        capa = '';

        for (var i=0; i< dados.length; i++) {
            var nome = CentovaApi.formataNomeMusica(dados[i]);
            if (!nome) {
                continue;
            }

            capa = nome.split('/').pop();

            console.log(baixarCapa(capa));

            html += '<tr>';
            html += '<td>' + baixarCapa(capa) + '</td>';
            html += '<td>' + (i+1) + 'º</td>';
            html += '<td>' + nome.split('/').pop() + '</td>';
            //html += '<td>' + dados[i].count + '</td>';
            html += '</tr>';
        }
        $('#table_top_musicas').find('tbody').html( html );
    }, true);
},

Everything works, with this exception of the covers, only undefined appears.

    
asked by anonymous 04.02.2015 / 03:38

1 answer

4

Its function baixarCapa returns undefined because you do not specify any return on it. You specify a return in a callback passed to it, but it only runs later (it is asynchronous ), and you can not capture its return.

Since you only get the data in that callback , you need to use it right there, either directly, or by calling another function and passing that data forward. And so you can not put the HTML in the way you're doing, which you hope the cover is already available. What you can do is book a place for the cover in HTML, but just put the image later.

For example, you can do this:

baixarCapa(capa, i);
html += '<td data-capa="' + i + '"></td>';

With a function like this:

function baixarCapa(capa, item) {
   $.getJSON("https://ajax.googleapis.com/ajax/services/search/images?callback=?", {
       q: '"' + capa + '"',
       v: '1.0'
   }, function(data) {
       var url = data.responseData.results[0].url;
       $('[data-capa=' + item + ']').html('<img src="' + url + '">');
   });
}
    
04.02.2015 / 03:54