1

For some reason, "p" returns as undefined. How would I make it return the array?

function doT() {
    var pe;
    $.get("https://www.google.com", function(data) { 
    pe = ["a", "b", "c"]; 
    });
    return pe;
}

var p = doT();
setTimeout(function() { console.log(p.length); }, 1200);

2 Answers2

2

One of the ways will be to use promise (read about it):

Right now it goes to the reject block because of CORS (read about it):

var promise = new Promise(function(resolve, reject) {
  var pe;
  $.ajax("https://www.google.com")
    .done(function() {
      pe = ["a", "b", "c"];
      resolve(pe);
    })
    .fail(function() {
      reject("error");
    });
});
promise.then(function(result) {
  $("#testing").text(result);
}, function(err) {
  $("#testing").text(err);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testing"></div>

Just make a valid ajax call and it will work. Comment if need further explanation.

Ajay Narain Mathur
  • 5,326
  • 2
  • 20
  • 32
0
function doT() {

  var pe = $.get("https://www.google.com", function(data) { 
    pe = ["a", "b", "c"]; 
  });

 return pe;
}

alert(doT());
br3nt
  • 9,017
  • 3
  • 42
  • 63