我使用异步函数设置 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;
}
}