Wait for the end of TWO asynchrounous functions be

2019-08-30 16:51发布

问题:

I'm trying to understand jQuery's Deferred, but inspite of samples, I can't achieve what I want to do.

So, I'd like to call 2 functions asynchrounously, and, when BOTH are ended, call another one.

Here's my code

function1();
function2();

function3();

function1() and function2() make an ajax call to my ASP.NET application, and they perfectly work. They must be ended before function3() starts.

I'm reading and reading again the documentation but function3() doens't wait for the end of the two others. Could you please provide my some sample in order to I understand Deferred ? I really need them to finish an important part of my project.

Thank you very much.


BONUS QUESTION

I've read about .when deferred... It is possible to write in some <div> element something like function1() running, then function2() running etc... ?

UPDATE

More details about function1() and function2() : They are very similar, here are they body :

function function1() {
    return $.ajax({
        url         :   "@Url.Action("MyMethod", "MyController")",
        contentType :   "application/json; charset=utf-8",
        dataType    :   "json"
    }).done(function(data) { 
        $.each(data, function(index) {
            pushDatas(data[index]);
        })
    }).fail(function (result) {
        alert("function1failed");
    });
}

function pushDatas(data)
{
    if(!($.inArray(data, loadedDatas) !== -1)) {
        loadedDatas.push(data);
    }
}

UPDATE 2

The functions are called like this :

<script type="text/javascript">
    $(document).ready(function () {
        //some others asynchrounous functions

        $.when(function1(), function2()).done(function3("test"));
    }

    ...

</script>

回答1:

function1 and function2 must return promise objects for this to work. For example,

function function1 () {
    return $.ajax({...});
}

now you can use $.when

$.when(function1(),function2()).done(function3);

Edit: or:

$.when(function1(),function2()).done(function(){
    function3("test");
});