【发布时间】:2020-09-20 07:22:27
【问题描述】:
我有一个自定义模板类/对象,结合了 JQuery 和纯 JS。
function tplObject (url) {
this.type = "tplObject";
this.includePath = "tpl/";
this.url;
this.template;
this.output;
this.openTpl (url);
}
tplObject.prototype = {
openTpl: function (url) {
if (url.split(".").length == 1) url = url + '.tpl';
this.url = url;
$.ajax ({
origin: this,
type: "GET",
url: this.includePath + url + '?' + window.config.cacheVersion,
async: false,
success: function (reply) {
this.origin.template = reply;
this.origin.output = reply;
}
});
},
...lots of functions that manipulate this.output;
getOutput: function () {
this._clear();
return this.output;
},
我可以操纵 tpl 对象,或者用另一个填充一个,重复填充,等等,像这样:
var tpl1 = new tplObject ('tplFile');
tpl.changeVar ('from', 'to');
var tpl2 = new tplObject ('tplPart');
tpl1.fill (tpl2);
$('body').html(tpl1.getOutput());
我一直在尝试使用承诺和等待的不同方法,但在 openTpl 函数响应之前,我无法让脚本在主流中等待。
我很想使用 fetch(),因为我也使用 service worker。响应可以被缓存,所以当我想操作模板的新版本时,我不必重新加载。
非常欢迎任何帮助!
对英格丽德表示敬意
【问题讨论】:
-
这会变得很复杂。你说“......很多操作 this.output; 的函数”,但
this.output是异步派生的。因此,许多/所有函数都需要是异步的,即它们需要返回一个 Promise,(可能需要解析为output); -
感谢回复,我还没这么看,一直在尝试解决再继续。但实际上并非如此,我可以在 getOutput 中解析,而其他数据正在加载,所以我需要调用所有模板的 Promise 链并构建发布最终产品。深思熟虑,谢谢。 -英格丽德
标签: javascript jquery promise async-await fetch