【发布时间】:2016-07-24 04:22:06
【问题描述】:
我正在尝试将一系列模板加载到一个数组中,但在使用 jQuery 的 when 方法时遇到了一些问题(基于 this answer)
var files = [/*array of file names*/];
var templates = [];
files.forEach(function(file){
templates.push(
$.get('/temps/' + file + '.hbs').then(function(temp) {
console.log('done loading', temp);
})
)
});
$.when.apply($, templates).then(function() {
console.log(arguments); //"undefined"x10
});
为什么不给when 的承诺数组生成我的十个模板的数组?这里出了什么问题?
编辑:
显然,在每个 get 中丢弃 then 方法让我更接近一点:
templates.push($.get('/temps/' + file + '.hbs'));
但是我很好奇我什么时候不能在这里使用then,以及什么时候
templates.push($.get('/temps/' + file + '.hbs')[0])
仍然给了我undefineds 的数组。返回数组中的第一个元素是返回的数据。为什么推送第一个元素不起作用?
【问题讨论】:
标签: javascript jquery promise deferred