jQuery: wait for function to complete to continue processing?

后端 未结 9 1112
轮回少年
轮回少年 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:04

    The short answer is that you can't block on an asynchronous operation...which is of course, the meaning of "asynchronous".

    Instead, you need to change your code to use a callback to trigger the action based on the data returned from the $.getJSON(...) call. Something like the following should work:

    $(function() {
      GetResults();
    });
    
    function GetResults() {
      $.getJSON("/controller/method/", null, function(data) {
        for(var i = 0; i < data.length; i++) {
          // Do stuff with data
        }
      });
    }
    
    0 讨论(0)
  • 2020-12-06 01:08

    Ajax already gives you a callback, you are supposed to use it:

    function dostuff( data ) {
        for(var i = 0; i < data.length; i++) {
            // Do stuff with data
        }
    };
    $(document).ready( function() {
        $.getJSON( "/controller/method/", null, dostuff );
    });
    
    0 讨论(0)
  • 2020-12-06 01:09

    You could do this:

    $(function() {
        PerformCall();        
    });
    
    function PerformCall() {
       $.getJSON("/controller/method/", null, function(data) {
           for(var i = 0; i < data.length; i++) {
            // Do stuff with data
           }
       });
    }
    
    0 讨论(0)
  • 2020-12-06 01:12

    This is not possible.

    Either you make your function synchronous or you change the design of your code to support the asynchronous operation.

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

    You can have a callback with parameters that should work nicely...

    $(function() {
        GetResults(function(data) {
          for(var i = 0; i < data.length; i++) {
            // Do stuff with data
          }
        });
    
    });
    
    function GetResults(func) {
       $.getJSON("/controller/method/", null, func);
    }
    
    0 讨论(0)
  • 2020-12-06 01:14

    I've run into something similar before. You'll have to run the ajax call synchronously.

    Here is my working example:

    $.ajax({
        type: "POST",
        url: "/services/GetResources",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: '{resourceFileName:"mapedit",culture:"' + $("#lang-name").val() + '"}',
        cache: true,
        async: false, // to set local variable
        success: function(data) {
            localizations = data.d;
        }
    });
    
    0 讨论(0)
提交回复
热议问题