-3

My question is sorta linked to this answer.

I've tried to the same thing here below but it still says that its undefined.

function Get(callback) {
    var xhr = new XMLHttpRequest();
    
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status === 200) {
        callback(null, xhr.response);
      } else {
        callback(status, xhr.response);
      }
    };
    xhr.open('GET', 'https://search.mtvnservices.com/typeahead/suggest/?solrformat=true&rows=20&q=alexander+mccormick%20AND%20schoolid_s%3A1262&defType=edismax&qf=teacherfirstname_t%5E2000%20teacherlastname_t%5E2000%20teacherfullname_t%5E2000%20autosuggest&bf=pow(total_number_of_ratings_i%2C2.1)&sort=total_number_of_ratings_i%20desc&siteName=rmp&rows=20&start=0&fl=pk_id%20teacherfirstname_t%20teacherlastname_t%20total_number_of_ratings_i%20averageratingscore_rf%20schoolid_s&fq=', true);
    xhr.send();
};

var result;
Get(function (err, result) {
    result = result.response.docs.map(doc => doc.averageratingscore_rf);
});
console.log(result);
}

I know for a fact that it does grab what I want cause when I adjust the code to this

Get(function (err, result) {
    console.log(result.response.docs.map(doc => doc.averageratingscore_rf));
});

The output is not undefined and it says its 2.3 which is what I want the variable result to be.

Community
  • 1
  • 1
Dp4897
  • 25
  • 5
  • You have two things named `result` in the last 5 lines of your code: the variable define by `var result` and the parameter defined by `function (err,result)`. Rename the latter to `function(err,xhrResult)` and rewrite the next line to read: `result = xhrResult.response...` - and it should work (it I understood your intent :-p). – moilejter Aug 18 '18 at 23:36
  • If you're wondering why the very last console log is displaying undefined it's perfectly normal. The Get function is asynchronous and does not block executions when it's called. Only the callback will be called with the result. Here by the time console.log is executed (just after Get is called since it does not block), the result has not yet been returned. – remix23 Aug 18 '18 at 23:36
  • @moilejter Just tried that and it still says undefined when I try to console.log(result); outside of that function – Dp4897 Aug 18 '18 at 23:46
  • @remix23 - good catch! – moilejter Aug 18 '18 at 23:51
  • @remix23 Well how am I suppose to store the variable I get from the function? It grabs the variable when i console log it within the function but when I console log it outside the function its undefined – Dp4897 Aug 19 '18 at 00:00
  • you're already storing it in the callback you pass to the Get function: `res = result.response.docs.map(doc => doc.averageratingscore_rf);` I've purposedly changed result to res since the 2nd callback parameter is result. It's just not YET available when you call `console.log` – remix23 Aug 19 '18 at 00:06

2 Answers2

0

Wrap it around a promise,

function Get(callback) {
    return new Promise(function(res){
        var xhr = new XMLHttpRequest();

        xhr.responseType = 'json';
        xhr.onload = function() {
          var status = xhr.status;
          if (status === 200) {
            res(callback(null, xhr.response));
          } else {
            res(callback(status, xhr.response));
          }
        };
        xhr.open('GET', 'https://search.mtvnservices.com/typeahead/suggest/?solrformat=true&rows=20&q=alexander+mccormick%20AND%20schoolid_s%3A1262&defType=edismax&qf=teacherfirstname_t%5E2000%20teacherlastname_t%5E2000%20teacherfullname_t%5E2000%20autosuggest&bf=pow(total_number_of_ratings_i%2C2.1)&sort=total_number_of_ratings_i%20desc&siteName=rmp&rows=20&start=0&fl=pk_id%20teacherfirstname_t%20teacherlastname_t%20total_number_of_ratings_i%20averageratingscore_rf%20schoolid_s&fq=', true);
        xhr.send();
    })
};



 Get(function (err, result) {
        return result.response.docs.map(doc => doc.averageratingscore_rf);
    })
   .then(function(result){
        //do whatever you want here
        console.log(result)
    });

If you work in ES5, create an object wrapper around ajax or write a recursive function to wait until the variable is available.

ibrahim tanyalcin
  • 5,643
  • 3
  • 16
  • 22
0

In javascript, you often do things asynchonously:

function Get(callback) {
    var xhr = new XMLHttpRequest();

    xhr.responseType = 'json';
    xhr.onload = function() {
        var status = xhr.status;
        if (status === 200) {
            callback(null, xhr.response);
        } else {
            callback(status, xhr.response);
        }
    };
    xhr.open('GET', 'https://search.mtvnservices.com/typeahead/suggest/?solrformat=true&rows=20&q=alexander+mccormick%20AND%20schoolid_s%3A1262&defType=edismax&qf=teacherfirstname_t%5E2000%20teacherlastname_t%5E2000%20teacherfullname_t%5E2000%20autosuggest&bf=pow(total_number_of_ratings_i%2C2.1)&sort=total_number_of_ratings_i%20desc&siteName=rmp&rows=20&start=0&fl=pk_id%20teacherfirstname_t%20teacherlastname_t%20total_number_of_ratings_i%20averageratingscore_rf%20schoolid_s&fq=', true);
    xhr.send();
};

var res;
Get(function (err, result) {
    res = result.response.docs.map(doc => doc.averageratingscore_rf);
    console.log('res has been set because the xhr call has returned, res: ', res);
});
console.log('res is not YET available, res: ', res);

The execution order will self explain in the console.

remix23
  • 2,632
  • 2
  • 11
  • 21
  • So I now get why res is not being set. What is the workaround so that res is set outside of the function and is a global set variable instead of only being defined within the function – Dp4897 Aug 19 '18 at 01:50
  • By declaring the variable (`var res;`) outside the function, which is the case here. The scope of a var is determined by where it's defined, not where it's set. if you want to make sure the variable is here and then do something with it, you need to do this something within the callback => maybe call another function just after setting res. – remix23 Aug 19 '18 at 10:11