jQuery: wait for function to complete to continue processing?

后端 未结 9 1127
轮回少年
轮回少年 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: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. :)

提交回复
热议问题