【问题标题】:JQuery replace async:false with promise with classesJQuery 用类替换 async:false 和 promise
【发布时间】: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


【解决方案1】:

使整个函数异步将是很多工作。因此,与此同时,我采用了这种旧式的 declare-your-variables-first 方法。

function fetchResources(processList) {
  return Promise.all(
    Object.keys(processList).map(function (i) {
      var obj = processList[i];
      return fetch(obj.fetchUrl)
      .then(r => r.text())
      .then(function (data) {
        obj.setData (data);
        return obj;
      })
      .catch(error => ({ error, obj }))
    })
  )
}  

在原始对象上调用 setData。 像这样应用。

fetchResources ([
  tpl1 = new tplObject ('tplFile'),
  tpl2 = new tplObject ('tplPart')
]).then (function () {
  tpl1.changeVar ('from', 'to');
  tpl1.fill (tpl2);
  $('body').html(tpl1.getOutput());
});

【讨论】:

  • 英格丽德,这是 JavaScript 吗? -> 运算符是什么?为什么在数组字面量中有赋值?
  • new(或其他方式)构造的任何东西都应该返回构造对象的实例,而不是Promise。构建完成后,可以调用异步的.init()方法。例如:let tpl1 = new tplObject('tplFile'); let tpl2 = new tplObject('tplPart'); Promise.all([tpl1.init(), tpl2.init()]) .then(function() { tpl1.changeVar('from', 'to'); tpl1.fill(tpl2); $('body').html(tpl1.getOutput()); });
  • 所以 -> 是一个混淆,我更正了它。 tpl1 和 2 是构造对象。 fetchResources 函数是返回承诺的函数。 fetchResources 被传入两个刚刚构建的对象,运行函数“setData”,然后返回对象。
猜你喜欢
  • 2020-12-18
  • 1970-01-01
  • 2017-03-02
  • 2014-01-08
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
  • 1970-01-01
  • 2017-10-09
相关资源
最近更新 更多