how to use jquery deferred with vktemplate / queuing ajax requests

五迷三道 提交于 2020-01-03 05:18:14

问题


Using vktemplate isn't quite working when I try to use jquery deferreds. Since the vktemplate makes an ajax call of its own, the deferred gets resolved before vktemplate completes its work, and its optional callback. How can I set up vk so that the promise doesn't get resolved until after these two things happen?

$(document).on('click', '.ajax', function() {
    $.when(ajax1('<p>first</p>'), 
           ajax2('<p>second</p>'), 
           ajax3('<p>third</p>'))
     .then(function(results1, results2, results3) {
        console.log(results1);
        $('.document').append(results1);
        $('.document').append(results2); 
        $('.document').append(results3);         
        alert('all ajax done');
    });
});

function ajax1(data) {

    $.ajax({
        type: 'post',
        url: 'templates/test_template.tmpl',
        data: "data=" + data,
        dataType: 'json',
        success: function (returnedData) {

            $('#resultsDiv').vkTemplate('templates/test_template.tmpl', returnedData, function () {
                //vk callback
                //possibly call my resolve here?
            });
        }
    });
}

function ajax2(data){//more of the same}

回答1:


Since vkTemplate returns nothing you need to manually create a deferred and resolve it in success callback with required data.

function ajax1(data) {
    var dfd = $.Deferred();

    $.ajax({
        type: 'post',
        url: 'templates/test_template.tmpl',
        data: "data=" + data,
        dataType: 'json',
        success: function (returnedData) {

            $('#resultsDiv').vkTemplate('templates/test_template.tmpl', returnedData, function (el, data, context) {
                dfd.resolveWith(context, [$(el)]);
            });
        }
    });

    return dfd.promise();
}


来源:https://stackoverflow.com/questions/13462455/how-to-use-jquery-deferred-with-vktemplate-queuing-ajax-requests

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