Wait until all jQuery Ajax requests are done?

后端 未结 21 1786
离开以前
离开以前 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:22

    To expand upon Alex's answer, I have an example with variable arguments and promises. I wanted to load images via ajax and display them on the page after they all loaded.

    To do that, I used the following:

    let urlCreator = window.URL || window.webkitURL;
    
    // Helper function for making ajax requests
    let fetch = function(url) {
        return $.ajax({
            type: "get",
            xhrFields: {
                responseType: "blob"
            },
            url: url,
        });
    };
    
    // Map the array of urls to an array of ajax requests
    let urls = ["https://placekitten.com/200/250", "https://placekitten.com/300/250"];
    let files = urls.map(url => fetch(url));
    
    // Use the spread operator to wait for all requests
    $.when(...files).then(function() {
        // If we have multiple urls, then loop through
        if(urls.length > 1) {
            // Create image urls and tags for each result
            Array.from(arguments).forEach(data => {
                let imageUrl = urlCreator.createObjectURL(data[0]);
                let img = ``;
                $("#image_container").append(img);
            });
        }
        else {
            // Create image source and tag for result
            let imageUrl = urlCreator.createObjectURL(arguments[0]);
            let img = ``;
            $("#image_container").append(img);
        }
    });
    

    Updated to work for either single or multiple urls: https://jsfiddle.net/euypj5w9/

提交回复
热议问题