0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

14 Comments

Thank you. Can you see my edit? Is this more correct?
This is working pretty well. However I'm trying to return this data to another function. $.when.apply($, templates).then(function() { return arguments }); and store the data in another variable. So, eg, all the ajax would be in a function doAjax() and I trying to do var templatesFromAjax = doAjax(), but I get undefined when on the next line I do `console.log(templatesFromAjax);
Yes, not using then at all is correct as well. Using [0] doesn't make sense, as promises don't have such a property.
You can use .then(function(){ return $.map(arguments, function(args) { return args[0]; }); }) to get an array of ajax results. jQuery.when is the horror when compared with promises with multiple return values.
@thomas: Probably you've got the arguments of the map callback in the scope view, not the arguments of the then callback.
|
-1

You're calling then which returns another promise. If you just want a "side effect" use done instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.