繁体   English   中英

创建具有其字段的对象取决于AJAX调用

[英]Creating an object that has it's field depend on AJAX calls

我正在尝试实例化服务层类“ foo”,该类将负责代表我的表示层将API调用分派到任何地方。 但是,“ foo”所需的必要资源只能通过对不同端点进行AJAX调用来获得。

例如,考虑foo是否需要获取当前登录用户的accountId才能完成请求。 但是,accountId仅可通过对端点“ bar”的网络调用获得。

因此,我需要将foo的调用与bar的链接在一起。

bar.getAccountId().then( (accountId) => { foo.getInformation(accountId) });

但这意味着foo需要发出请求时,它将首先被bar的网络呼叫阻止。 如果我们知道在用户访问网站期间,accountId不会改变,那么将accountId存储到foo字段中将是理想的选择。

即,在foo的构造函数中,我希望能够执行以下操作:

construtor() { bar.getAccountId().then( (accountId) => {this._accountId = accountId });

现在,只要foo需要进行调用,我就可以简单地使用_accountId而不是对bar进行网络调用,而只需对foo进行调用:

foo.getInformation() //we no longer need to supply an accountId, since it's cached inside foo.

但是,由于构造函数现在正在进行AJAX调用,因此我们无法知道调用是否已完成。 如果我们尝试这样做:

var foo = new Foo; foo.getInformation()

我们不能确定foo的构造函数是否已收到bar的响应。 我想到的一种解决方法是,也将诺言明确地缓存在构造函数中。 例如:

//CLASS FOO
constructor() {
  this._promise = bar.getAccountId().then((accountId) => {
    this._accountId = accountId;
  })
}

getInformation() {
  if (this._promise.hasResolved()) {
    return makeNetworkCall(this._accountId)
  } else {
    this._promise.then(() => {
      return makeNetworkCall(this._accountId);
    })
  }
}

我想知道是否存在解决此问题的设计模式,因为我敢肯定这种情况已经足够普遍了。

我会朝着将请求放入getInformation()调用的方向发展,并让它缓存调用的结果。 然后在以后的调用中,您可以检查是否有缓存的值,并使用缓存的值将已解决的承诺返回给调用方。

就像是:

//CLASS FOO
constructor() {
  this._accountId = null;
}

getInformation() {
  if (this._accountId !== null) {
      // If value cached, return resolved promise with value.
      return Promise.resolve(this._accountId);
  }

  // Otherwise, retrieve the value and cache it.
  return bar.getAccountId().then((accountId) => {
      this._accountId = accountId;
      return accountId;
  });
}

一般来说,构造器不是执行任何异步工作的好地方。 它应该初始化对象,而将繁重的工作留给其他功能。

您可以简单地创建一个init()方法来加载所有必要的数据并返回一个可以继续按预期使用的承诺:

var foo = new Foo; foo.init().then(()=> {
    // doMoreAsyncStuff();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM