我正在尝试将一系列模板加载到数组中,并且在使用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
的承诺数组生成我的十个模板数组?这里出了什么问题?
修改
显然,放弃每个then
中的get
方法让我更接近:
templates.push($.get('/temps/' + file + '.hbs'));
但是,当我在这里使用then
以及
templates.push($.get('/temps/' + file + '.hbs')[0])
仍然给了我一组undefined
个。返回数组中的第一个元素是返回的数据。为什么不推动第一个元素工作?
答案 0 :(得分:2)
因为数组中的promise是undefined
的承诺,而不是模板的承诺。你需要使用
$.get('/temps/' + file + '.hbs').then(function(temp) {
console.log('done loading', temp);
return temp;
// ^^^^^^
})
获取模板的承诺,否则使用隐式返回值undefined
解析。请记住,then
会为回调结果返回一个新的承诺,而不是原来的承诺。
答案 1 :(得分:-1)
你正在呼叫then
,它会返回另一个承诺。如果您只想要“副作用”,请改用done
。