简体   繁体   中英

Wrapping async cycle in Promise

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM