I'm trying to fire a function when all the templates are loaded. This is done via a loadTemplate function for each template.
My problem is how to listen for all the .then() to finish, and only after that to fire my foo() function.
I've tried using when() and promise, but I haven't been successful in binding that to the outside each, while I've manage to bind it to the loadTemplate (which isn't what I'm looking for).
I could always bind each loadTemplate to a counter, and on each iteration check if the counter has reached the number of templates on the each, but I'm sure there's a more elegant way to do this.
Here's the loop code:
$.each(templates.hbs, function(idx, template) {
loadTemplate(template.name)
.then(function(templateStr){
var compiledTemplate = Handlebars.compile(templateStr);
if(template.isPartial){
Handlebars.registerPartial(template.key, compiledTemplate);
}
templates[template.key] = compiledTemplate;
});
});
and the function to fire after:
function templateDone(){
console.log("done!");
}
Thanks for the help!
Edit: Including the loadTemplate code as well:
function loadTemplate (template) {
return new Promise(function (resolve, reject) {
$.ajax({
url: config.wwwroot + '/folder/' + template + '.hbs',
async: false,
success: function (result) {
resolve(result);
},
error: reject
});
});
}