然后使用 fetch 在 promise 中编译 handlebarsjs 模板

using fetch to then compile a handlebarsjs template inside a promise

使用 fetch 获取数据然后使用 Handlebars 执行它非常简单,当您已经编译了模板时..

var template        = Handlebars.compile(the-html);
fetch('data.json')
   .then(function(response) {
      return response.json();
   })
   .then(function(json) {
      var html = template(json[0]);
      // use this somehow
   });

但我想根据承诺链中预先确定的一些路径获取一些文件(包含 handlebars 标签的标记和脚本),并将它们编译为 Handlebars 模板,然后将它们应用到某个模型我之前准备好了,在promise链里面。

var json = {some-data};
some-promise-step()
.then(function(json) {
   var templates = Handlebars.templates = Handlebars.templates || {}; // global handlebars object
   var urls = ["/abc/templates/" + json.template + "/index.html", "/abc/templates/" + json.template + "/style.css", "/abc/templates/" + json.template + "/script.js"]; // simplified
   var promises = urls.map(function(url) {
      return fetch(url).then(function(response) {
         var name = response.url.split("/").pop();
         return response.text().then(function(data) {
            templates[name] = Handlebars.compile(data);
         });
      });
   });
   return Promise.all(promises);
}).then(function(result) { // result is an array of 'undefined' ?? hmm
  return Promise.all([
    zip.file("index.html", Handlebars.templates["index.html"](json)),
    zip.file("style.css", Handlebars.templates["style.css"](json)),
    zip.file("script.js", Handlebars.templates["script.js"](json)),
  ]);
}).then( // more steps 

Handlebars 需要编译成全局 Handlebars.templates[] 对象(已经存在)才能被下一步使用(其中 zip 对象被馈送到应用模板和 returns 承诺)

但是当提取返回并且 .text() 方法 returns 编译模板时,外部承诺已经解决并开始尝试使用模板。

我不希望最终的 .then( 在获取承诺全部解决之前开始做它需要做的事情...

啊哈!不要 return 获取承诺; return 在获取的 response.text() 承诺结束时解决的承诺。

var promises = urls.map(function(url) {
    return new Promise(function(resolve,reject) {
        fetch(url).then(function(response) {
            var name = response.url.split("/").pop();
            return response.text().then(function(html) {
                templates[name] = Handlebars.compile(html);
                resolve(name);
            });
        });
    });
});
return Promise.all(promises);

仍然可以进一步优化整个想法,但这似乎暂时有效。