Wait until all jQuery Ajax requests are done?

后端 未结 21 1783
离开以前
离开以前 2020-11-21 04:39

How do I make a function wait until all jQuery Ajax requests are done inside another function?

In short, I need to wait for all Ajax requests to be done before I exe

21条回答
  •  温柔的废话
    2020-11-21 05:31

    If you want to know when all ajax requests are finished in your document, no matter how many of them exists, just use $.ajaxStop event this way:

    $(document).ajaxStop(function () {
      // 0 === $.active
    });
    

    In this case, neither you need to guess how many requests are happening in the application, that might finish in the future, nor dig into functions complex logic or find which functions are doing HTTP(S) requests.

    $.ajaxStop here can also be bound to any HTML node that you think might be modified by requst.


    Update:
    If you want to stick with ES syntax, then you can use Promise.all for known ajax methods:

    Promise.all([ajax1(), ajax2()]).then(() => {
      // all requests finished successfully
    }).catch(() => {
      // all requests finished but one or more failed
    })
    

    An interesting point here is that it works both with Promises and $.ajax requests.

    Here is the jsFiddle demonstration.


    Update 2:
    Yet more recent version using async/await syntax:

    try {
      const results = await Promise.all([ajax1(), ajax2()])
      // do other actions
    } catch(ex) { }
    

提交回复
热议问题