Reputation: 55
I am just getting up to speed with typescript 1.5 and promises (currently using es6-promise from Jake Archibald): A few classes, one class instantiates the details class, which instantiates the common class, but I need the common class to complete before the details class can make its call. From what I understand, promises is the key to make this happen.... but struggling on how to get promises into the class and not just the class methods. Trying to avoid jQuery promises since, from what I have read, they do not follow promises/a+ exactly...
some pseudo-code:
export class UserData extends Promise<UserData> (?){
_cd = new CommonData();
*another ajax call, based on data returned obtained commondata call*
}
export class CommonData {
private _instance = this;
public Name: string= null;
constructor () {
*I want to make my class promisable, not just the methods*
new promise(function (resolve, reject) {
??
});
}
getData() {
var parentClass = this._instance;
return new Promise(function(resolve, reject) {
$.ajax({
success: {
...
parentClass.Name = *data from ajax*;
resolve();
},
error: {
reject();
}
}
}
}
export class UI {
var us = new UserDetails();
}
Upvotes: 1
Views: 7733
Reputation: 9798
If UserData is initialized asynchronously, then create a factory method that returns a Promise. In this case initUserData
is the factory method and the underlying constructor should not be used externally, although in TypeScript it can't be made private.
In general, as a guide for reactive programming, if you decide to program with Promises, expect to expose a Promise<T>
wherever a synchronously coded program would expose a T
. Not always true, sometimes you have have to block to resolve, but every such instance of blocking has a slight code smell that needs examination.
export class UserData {
constructor(commonData: CommonData) {
// Construct your UserData
}
initUserData(): Promise<UserData> {
Promise<CommonData> common = getCommonDataPromise();
return common.then(c => new UserData(c));
}
}
Upvotes: 2
Reputation: 276383
class UserData extends Promise (?){
No. Instead think composition: (not inheritance .. unless you are writing a new promise library ... which is not the case here)
class UserData {
public data;
constructor(){
doStuff().then(()=>this.data = new SomeData());
}
}
Upvotes: 3