jQuery deferred object with nested ajax calls

后端 未结 3 2025
一向
一向 2020-12-28 17:35

I have a situation in which my ajax calls must perform in a particular order. I have used jQuery Deferred objects in other situations, but cannot seem to find a way to make

3条回答
  •  死守一世寂寞
    2020-12-28 18:03

    You don't actually need an extra deferred object. You can do what you want by chaining with then():

    function nestedAjax() {
        return $.get("/echo/json/").then(function(result1){
            console.log("First ajax done.");
            if (result1) {
                return result1;
            } else {
                return $.get("/echo/json/").then(function(nestedResult){
                    console.log("Second ajax done.");
                    return nestedResult;
                });
            }
        });
    };
    

    I added some logic since I think that's probably the reason you are executing this synchronously. After that you can use the result in $.when like so:

    $.when(nestedAjax(), $.get("/something/else")).then(function(nested, other) {
        console.log("Complete.", nested, other);
    });
    

提交回复
热议问题