具有异步设置属性的 JS 对象

JS Object with an asynchronously set property

本文关键字:JS 对象 属性 设置 异步      更新时间:2023-09-26

我使用异步函数设置 Person.name(想想ajax调用)。不幸的是,我仍然想使用对象中的其他函数,而不必将它们放在回调中。

如何使用依赖于对象的异步设置属性的函数?

要执行的代码:

var user = new Person();
user.setName(); // This is async.
var is_jennifer = user.isItJennifer(); // Oh no! the user's name may not be defined yet!
...
...
var is_tom = user.isItTom(); // Much later in the code I need the async property again. I don't want to cram all of this into a callback whenever I setName.

具有异步方法setName()的对象。

function Person() {
  // Properties
  this.name = null;
  this.setName = function() {
    this.name = NameModelThing.getName(); // Oh no! getName returns a result asynchronously.
  }
  this.isItJennifer = function() {
    return (this.name == 'Jennifer') ? true : false;
  }
  this.isItTom = function() {
    return (this.name == 'Tom') ? true : false;
  }
}

如果你对 ajax 请求使用 jquery,你可以通过传递 async: false 作为一个选项来使请求不异步。

http://api.jquery.com/jQuery.ajax/

作为替代方法,您可以使用一种模式,在加载页面时对 Person 对象进行某种初始化,并从那里使用回调:

var user = new Person();
user.fetch({
  success: function() {
  // code when user ready here.
  }
});