简体   繁体   English

javascript同步ajax调用问题

[英]javascript sync ajax call issue

i ma trying to fetch list of names of htmls from ajax call and then for each html another ajax call and then i am trying to append it using handlebar. 我试图从ajax调用中获取html名称列表,然后为每个html进行另一个ajax调用,然后我尝试使用车把附加它。 but this is not happening with below code. 但是下面的代码不会发生这种情况。 can somebody help me in debugging it : 有人可以帮我调试一下吗:

$.getJSON('api/filterTemplate/' + pageName.page, function (data) {
    var promises = [];
    $.each(data, function (i, rec) {
        promises.push($.get('commonCore/templates/' + rec.templateHtml));
    });
    $.when.apply(this, promises).then(function() { //after all requests complete
        $.each(arguments, function(i, html) {
            var filterTemplate = Handlebars.compile(html);
            replaceFilterTemplate(filterTemplate,data[i].classids);// this functions appends html to div -data[i].classids
        })
    })
});

after each html is fetched it should be appended and then next call should happen 在获取每个html之后,应将其附加,然后再进行下一次调用

$.get returns the jqXHR Object. $.get返回jqXHR对象。 That's what you're actually adding to your promises array. 那就是您实际上要添加到promises数组中的内容。

You should use synchrone calls, or reformat your code to handle all the fetches async and then proceed through the promises. 您应该使用同步调用,或重新格式化代码以处理所有异步获取操作,然后继续执行Promise。

Synchrone alternative: 同步替代品:

$.each(data, function (i, rec) {
    $.ajax({
        url: 'commonCore/templates/' + rec.templateHtml, 
        async: false,
        success: function(result) {
             promises.push(result);
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM