Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用fetch在promise中编译handlebarsjs模板_Javascript_Promise_Fetch Api - Fatal编程技术网

Javascript 使用fetch在promise中编译handlebarsjs模板

Javascript 使用fetch在promise中编译handlebarsjs模板,javascript,promise,fetch-api,Javascript,Promise,Fetch Api,使用fetch获取数据,然后使用手柄执行数据,这在您已经编译模板的情况下非常容易 var template = Handlebars.compile(the-html); fetch('data.json') .then(function(response) { return response.json(); }) .then(function(json) { var html = template(json[0]); // u

使用
fetch
获取数据,然后使用手柄执行数据,这在您已经编译模板的情况下非常容易

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
   });
但是我想根据承诺链中预先确定的路径获取一些文件(包含Handlebar标记的标记和脚本),并将它们编译为Handlebar模板,然后将它们应用到承诺链中我之前准备的一些模型

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 
Handlebar需要编译为全局Handlebar.templates[]对象(已存在),然后才能用于下一步(在该步骤中,
zip
对象将输入应用模板的输出并返回承诺)

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


我不想要最后的
。然后(
开始做它需要做的事情,直到回迁承诺全部解决之后…

啊哈!不要返回回迁承诺;返回回迁响应结束时解决的承诺。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);
仍然可以进一步优化整个想法,但这似乎暂时可行。

这看起来,呃,很有希望。。。