【问题标题】:using fetch to then compile a handlebarsjs template inside a promise使用 fetch 然后在 Promise 中编译一个 handlebarsjs 模板
【发布时间】:2017-10-24 05:56:28
【问题描述】:

使用 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
   });

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

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 对象被输入应用模板的输出并返回一个承诺)

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

我不希望最终的 .then( 开始做它需要做的事情,直到 fetch 承诺全部解决...

【问题讨论】:

标签: javascript promise fetch-api


【解决方案1】:

啊哈!不要返回 fetch 承诺;返回一个在 fetch 的 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);

仍然可以进一步优化整个想法,但这似乎目前可行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2012-09-04
    相关资源
    最近更新 更多