Question

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>
Was it helpful?

Solution

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");
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top