Reputation: 915
I'm trying to do something like:
console.log("start spinner!");
for (var i = 0; i < modules.length; ++i) {
var filename = modules[i].filename;
$.get('./views/templates/'+ filename ).done(function(data){
modulesTemplates.push(data);
console.log(data);
}).fail();
}
How do I do for having a callback or wrapping this whole cycle in a promise? I tried with bluebirdjs, something like:
Promise.all([ modulesTemplates ])
.then(function(data){
console.log(course.modulesTemplates);
loadView('home.html');
console.log("stop spinner!");
});
But it doesn't work. Am I missing something or is it a better way of doing this?
The sequence of the console.logs:
start spinner!
[]
stop spinner!
tempalte 1
template 2
Upvotes: 1
Views: 113
Reputation: 276406
With bluebird, assuming the requests can be in flight at once, you can do something like:
console.log("Start Spinner");
Promise.map(modules, function(module){
return $.get('./views/templates/' + module.filename);
}).then(function(modulesTemplates){
// module template is a list of all the templates loaded here
// this code will be reached after all are loaded, for example
// modulesTemplates[0] is the first template.
console.log("Stop Spinner");
});
Upvotes: 3