如何将.when()与包含ajax调用的函数一起使用?

时间:2013-06-25 19:18:28

标签: javascript jquery ajax

我已经看到.when().then()在jquery中直接使用.ajax调用来延迟回调函数的执行,直到完成ajax。我遇到的问题是对不是ajax调用的函数做同样的事情,但是包含一个ajax函数。我有以下代码:

$(function() {

    $('.document').on('click', '.ajax', ajaxFunction);

});

function ajaxFunction(e) {
        e.preventDefault();

        // ajax request
        $.ajax({
            async: true,
            cache: false,
            type: 'post',
            url: '/echo/html/',
            data: {
                html: '<p>This is echoed the response in HTML format</p>',
                delay: 1
            },
            dataType: 'html',
            beforeSend: function() {
                console.log('Fired prior to the request');
            },
            success: function(data) {
                console.log('Fired when the request is successfull');
                $('.document').append(data);
            },
            complete: function() {
                console.log('Fired when the request is complete');
            }


        });

        console.log('hello world!');
    }

function defferedFunction(d){
    $.when(ajaxFunction(e)).then(alert('hi mom!'))
}

我的目标是在ajaxFunction功能的内容完成时发出警报('嗨妈妈!'),即当ajax完成并且'hello world!'时已登录到控制台。但是,警报永远不会出现。

据我所知,问题是容器函数实际上并没有返回一个promise,因此.then()部分永远不会触发。当所有内部代码(包括ajax)完成后,如何修改此代码以返回promise?

我希望继续使用.when() / .then()模式,而不是在ajaxFunction中手动包含回调。

以上示例的小提示是here.

3 个答案:

答案 0 :(得分:3)

您可以退回承诺

function ajaxFunction(e) {
        e.preventDefault();

        // ajax request
     return $.ajax({       // return promise  
            async: true,
            cache: false,
            type: 'post',
            url: '/echo/html/',

答案 1 :(得分:1)

有几件事。就像@pXL所说,你需要回复承诺。同样在你的小提琴中你需要将(d)参数从你的defferedFunction传递给你的ajaxFunction。最后改变你的.then to .done(function(a){});

http://jsfiddle.net/mq4Sj/5/

$(function() {

    $('.document').on('click', '.ajax', defferedFunction);

});

 function defferedFunction(e){
        $.when(ajaxFunction(e)).done(function(d){
        alert(d); // ->> response from server.
 })
    }

答案 2 :(得分:0)

我发现我可以通过为整个函数创建一个延迟事件,为我想要捕获的非ajax行为的延迟事件,在非ajax事件完成后解析第二个延迟事件,然后使用$.when()捕获何时解析ajax调用返回的延迟对象以及我为非ajax创建的延迟对象,然后使用.then()解析整个函数的延迟对象。

看起来像是这样,所有这些都放在一起:

$(function() {

    $('.document').on('click', '.ajax', defferedFunction);

});

function ajaxFunction(e) {
        e.preventDefault();

        // ajax request
        var ajaxDeferred = $.ajax({
            async: true,
            cache: false,
            type: 'post',
            url: '/echo/html/',
            data: {
                html: '<p>This is echoed the response in HTML format</p>',
                delay: 1
            },
            dataType: 'html',
            beforeSend: function() {
                console.log('Fired prior to the request')

            },
            success: function(data) {
                console.log('Fired when the request is successfull');
                $('.document').append(data);
            },
            complete: function() {
                console.log('Fired when the request is complete');
            }
        })

        var newDeferred = $.Deferred()

        var timeoutDeferred = $.Deferred()

        setTimeout(function(){
            console.log('hello world!')
            timeoutDeferred.resolve()
        }, 2000)

        $.when(timeoutDeferred, ajaxDeferred).then(function(){
            newDeferred.resolve()
        }
        );


        return newDeferred;
    }

function defferedFunction(e){
    $.when(ajaxFunction(e)).done(function(){alert('all done!')})
}