2016-09-18 135 views
0

我现在已经掌握了这一点代码,在那里我得到了页面所需的所有模板。ajax的承诺

问题是这样,每次我加载页面时,ajax请求都没有以相同的顺序完成。

有没有办法使用承诺或其他东西,使加载顺序始终保持不变?
谢谢。

var loadTemplates = function (templatesObject) { 
    $.each(templatesObject.template, function (index, template) { 
     template.callback = template.callback || $.noop; 

     $.ajax({ 
      url: template.url, 
      success: function(html) { 
       var compiledHtml = Handlebars.compile(html); 
       var output = compiledHtml(template.data); 
       $(template.target).append(output); 
       template.callback(); 
      } 
     }); 
    }); 
}; 

编辑:这是我的对象看起来像怎样,不同数量的模板,在这个例子中只有2。

templatesObject

var templates = { 
    template: [ 
     { 
      url: 'firsturl', 
      target: '#page-content' 
     }, 
     { 
      url: 'myurl', 
      target: '#page-content', 
      data: data, 
      callback: awesomefunction 
     } 
    ] 
}; 

回答

0

你可以使用一个事实,即$就返回一个承诺,使用$ .MAP而不是$。每次,并使用$。当等待所有的AJAX完成,并做你在$ .when(),然后回调成功回调...

var loadTemplates = function (templatesObject) { 
    $.when.apply($, $.map(templatesObject.template, function (index, template) { 
     template.callback = template.callback || $.noop; 
     return $.ajax({ 
      url: template.url, 
     }).then(function(html) { 
      return {html: html, template: template}; 
     }); 
    })).then(function() { 
     $.each(arguments, function(index, result) { 
      var compiledHtml = Handlebars.compile(result.html); 
      var output = compiledHtml(result.template.data); 
      $(result.template.target).append(output); 
      result.template.callback(); 
     }) 
    }); 
}; 
+0

感谢您的答案,但是当我控制台登录模板的时候,我得到0而不是模板对象。 我添加了一个我的对象看起来像是什么样子的例子,如果它有任何帮助。谢谢 –

+0

每个参数都是一个数组,数据是该数组的第一个元素。另外'arguments'就是数组像对象 – charlietfl

+0

d'oh,是的 - 我没有完全读取代码 –