Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Sort of like this:

function getfoo() {
  var foo = "";
  $.get("foofile.html", function (data) {
    foo = data;
  });
  return foo;
}

But then since the script is asynchronous, it will return "". That's obviously not what I want.

So then I tried this:

function getfoo() {
  var foo = "";
  $.get("foofile.html", function (data) {
    foo = data;
  });
  for (;;) {
    if (foo != "") {
      return foo;
      break;
    }
  }
}

And I expected that to work, but it didn't. Why not? And can someone suggest a solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
889 views
Welcome To Ask or Share your Answers For Others

1 Answer

You should use a callback pass to the function and let it deal your data.

function getfoo(callback) {
  var foo = "";
  $.get("foofile.html", function (data) {
    callback(data);
    // do some other things
    // ...
  });
}

getfoo(function(data) {
   console.log(data);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...