Search code examples
javascriptjqueryjsonget

Why does the script work line by line, but does not work as a whole?


If I run this script all by Chrome Console - I get error

Uncaught TypeError: Cannot read property 'playlist' of undefined

var owner = "yamusic-trending"
var kind = "1000"
var url = `https://music.yandex.ru/handlers/playlist.jsx?owner=${owner}&kinds=${kind}&light=false`

json = $.getJSON(url)
var tracks = json.responseJSON["playlist"]['tracks']

By if line by line

json = $.getJSON(url)

And then

var tracks = json.responseJSON["playlist"]['tracks']

Error is not. Why?


Solution

  • $.getJSON is aynchronous call and you need to wait until it get completed. If any of the operation dependes on the result return by this call then it should be handled in callback function.

    see below code

    ES5

        $.getJSON(url, function(data){
           var tracks = data.responseJSON["playlist"]['tracks']
        });
    

    ES6

    $.getJSON(url, json => {
      var tracks = json.responseJSON["playlist"]['tracks']
    });
    

    getJSON API Documentation