使用jQuery与promises数组

时间:2016-04-04 14:44:09

标签: javascript jquery promise deferred

我正在尝试将一系列模板加载到数组中,并且在使用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个。返回数组中的第一个元素是返回的数据。为什么不推动第一个元素工作?

2 个答案:

答案 0 :(得分:2)

因为数组中的promise是undefined的承诺,而不是模板的承诺。你需要使用

$.get('/temps/' + file + '.hbs').then(function(temp) {
    console.log('done loading', temp);
    return temp;
//  ^^^^^^
})

获取模板的承诺,否则使用隐式返回值undefined解析。请记住,then会为回调结果返回一个新的承诺,而不是原来的承诺。

答案 1 :(得分:-1)

你正在呼叫then,它会返回另一个承诺。如果您只想要“副作用”,请改用done