0

I am hitting an API and would like to isolate the data contained in responseJSON returned from it. console.log(mydata) yields undefined, despite it clearly being there when I do console.log(a) (see screenshot).

My code:

function onComplete(a){ 
    console.log(a);
    return a['responseJSON']
}
function getData(whenDone){
     var data = $.get('http://127.0.0.1:5000/');
         whenDone(data);

}
var mydata= getData(onComplete)
console.log(mydata);

enter image description here

user2242044
  • 8,803
  • 25
  • 97
  • 164
  • `$.get()` is asynchronous: it returns a promise (jqXHR) object, not the data directly, so you'll need to restructure your code a bit to allow for the asynchronousnous. – nnnnnn Nov 07 '17 at 01:52
  • @nnnnn somewhat new to this, can you explain how to get get the data from the promise object? – user2242044 Nov 07 '17 at 01:55
  • I've closed this as a duplicate - the linked question covers this very comprehensively, but the short story is you can say `$.get(...).done(function(result) { /* use result here */ })`. The accepted answer on that question is very good, but very long, so you may find [this answer](https://stackoverflow.com/a/23819901/615754) gets you going faster. – nnnnnn Nov 07 '17 at 01:57

0 Answers0