在 Promise 中包装异步循环

Wrapping async cycle in Promise

我正在尝试做类似的事情:

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();
}

如何进行回调或将整个周期包装在 promise 中? 我尝试使用 bluebirdjs,类似于:

Promise.all([ modulesTemplates ])
      .then(function(data){
           console.log(course.modulesTemplates);
           loadView('home.html');
           console.log("stop spinner!");
});

但是没用。我是不是遗漏了什么,或者这是更好的方法吗?

console.logs的顺序:

start spinner!
[]
stop spinner!
tempalte 1
template 2

使用 bluebird,假设请求可以同时运行,您可以执行以下操作:

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");
});