jQuery: wait for function to complete to continue processing?

后端 未结 9 1117
轮回少年
轮回少年 2020-12-06 00:28

Hey all. I have, what appears to be, a trivial problem. I have the following JavaScript:

$(function() {
    var r = GetResults();

    for(var i = 0; i <         


        
9条回答
  •  旧巷少年郎
    2020-12-06 01:15

    move your "do stuff with r" block into your $.getJSON callback. you can't do stuff with r until it has been delivered, and the first opportunity you'll have to use r is in the callback... so do it then.

    $(function() {
        var r = GetResults();  
    });
    
    function GetResults() {
       $.getJSON("/controller/method/", null, function(data) {
           for(var i = 0; i < data.length; i++) {
               // Do stuff with data
           }
           return data;
       });
    }
    

提交回复
热议问题