简体   繁体   中英

jQuery wait till function finishes

I have this script:

var d;
$(".circle").click(function() {
    var id = $(this).attr('id');
    var MyDiv1 = document.getElementById(id);
    var name = MyDiv1.innerHTML;

    $.get("url", function(data){
    d=data;
    });

    d=d.split(",");
    var arrayLength = d.length;
    for (var i = 0; i < arrayLength; i++) {
        if(i==id)
         custom_alert(d[i], name);
    }
});

I want to call

d = d.split(",");

Only after I'm sure d isn't undefined .
How do I execute that after the $.get functions finishes and d is assigned to the data?

You could simply put it into the callback? :

    $.get("url", function(d){
         d=d.split(",");
         var arrayLength = d.length;
         for (var i = 0; i < arrayLength; i++) {
           if(i==id)
            custom_alert(d[i], name);
         }
    });

Or using ES7 (very new stuff) :

(async function(){
var d=await new Promise(function(r){
  $.get("url",r);
});
d=d.split(",");
...
})();

You need to put the JS that depends on d being defined inside the get callback.

var d;
$(".circle").click(function() {
var id = $(this).attr('id');
var MyDiv1 = document.getElementById(id);
var name = MyDiv1.innerHTML;

$.get("url", function(data){
d=data;

   d=d.split(",");
   var arrayLength = d.length;
   for (var i = 0; i < arrayLength; i++) {
    if(i==id)
     custom_alert(d[i], name);
   }
 });
});

jQuery.get() is asynchronous because it is a shorthand for jQuery.ajax() who's default option for requests is async: true .

Read here about asynchronous requests.

// declare it here if you need its values later (to be a global variable), or move it inside function(){ } declared inside $.get() call.
var d;
$(".circle").click(function() {
    var id = $(this).attr('id');
    var MyDiv1 = document.getElementById(id);
    var name = MyDiv1.innerHTML;

    $.get("url", function(data){
         d=data;
         // $.get has an asynchronous answer (you don't know when it will come or if it comes). Call d.split here
         d=d.split(",");
         var arrayLength = d.length;
         for (var i = 0; i < arrayLength; i++) {
             if(i==id)
              custom_alert(d[i], name);
        }
    }); 
 });

You can only rely on d to have a value in the block where it is assigned a value, which is inside the callback function(data){...} .

var d;
$(".circle").click(function() {
  var id = $(this).attr('id');
  var MyDiv1 = document.getElementById(id);
  var name = MyDiv1.innerHTML;

  $.get("url", function(data){
    d=data.split(",");
    var arrayLength = d.length;
    for (var i = 0; i < arrayLength; i++) {
      if (i==id)
        custom_alert(d[i], name);
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM