【发布时间】: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 承诺全部解决...
【问题讨论】:
-
这看起来,呃,很有希望...stackoverflow.com/a/31425139/1238884
标签: javascript promise fetch-api