jQuery: wait for function to complete to continue processing?

后端 未结 9 1113
轮回少年
轮回少年 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;
       });
    }
    
    0 讨论(0)
  • 2020-12-06 01:23

    Given your updated requirements ...

    I cannot move the for loop processing into the callback function of the JSON request because I am reusing the functionality of GetResults several time throughout the page, unless I want to duplicate the code. Any ideas?

    ... you could modify GetResults() to accept a function as a parameter, which you would then execute as your $.getJSON callback (air code warning):

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

    As you can see from the general tide of answers, you're best off not trying to fight the asynchronous jQuery programming model. :)

    0 讨论(0)
  • 2020-12-06 01:28

    Move the data processing into the callback:

    $(function() {
        GetResults();
    });
    
    function GetResults() {
       $.getJSON("/controller/method/", null, function(data) {
    
           for(var i = 0; i < data.length; i++) {
               // Do stuff with data
           }
       });
    }
    
    0 讨论(0)
提交回复
热议问题