Wait for the end of TWO asynchrounous functions before firing a third (jQuery Deferred ?)

喜欢而已 提交于 2019-12-11 20:49:48

问题


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");
});


来源:https://stackoverflow.com/questions/19234699/wait-for-the-end-of-two-asynchrounous-functions-before-firing-a-third-jquery-de

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!