Search code examples
javascriptjquerypromisedeferred

Using jQuery when with array of promises


I'm trying to load a series of templates into an array and having some trouble with jQuery's when method (based on 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
});

Why doesn't giving the array of promises to when produce an array of my ten templates? What's gone wrong here?

Edit: Apparently, discarding the then method within each get gets me a little closer:

templates.push($.get('/temps/' + file + '.hbs'));

However I'm curious when I can't use then here, and also when

templates.push($.get('/temps/' + file + '.hbs')[0]) 

still gives me an array of undefineds. The first element in the returned array is the returned data. Why won't pushing that first element work?


Solution

  • Because the promises in the array are promises for undefined, not promises for your templates. You'll need to use

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

    to get a promise for the template, otherwise it resolve with the implicit return value undefined. Remember that then returns a new promise for the result of the callback, not the original promise.