Reputation: 788
I've got myself tangled up in Promises. I want to wait until checkNewVersion() has finished and then execute the then statement, but at the moment, 'finished' gets called first then 'api response'
page.ts
public ionViewDidLoad() {
this.platform.ready()
.then(() => {
this.versionChecker.checkNewVersion()
.then(response => {
console.log('finished')
})
});
}
version-checker.ts
public checkNewVersion(force?: boolean): Promise<CheckResult> {
let platform = this.platform.is("ios") ? 'ios' : 'android';
if (force || this.shouldCheck()) {
return this.checkPromise = this.api.post('check-version', {platform: platform, version: '0.2.1'})
.then(response => {
console.log('api response')
let result = {
latest: response.latest,
}
return result;
});
}
return this.checkPromise;
}
api-service.ts
public post(path: string, body: any): Promise<any> {
//add location if we have it.
let postBody = {...body};
postBody.locationInfo = this.locationService.getUpdatedLocation();
return this.http.post(this.settings.api + path, postBody, { headers: this.headers })
.map((res: Response) => { return res.json(); })
.catch((err: Response, obs: Observable<any>) => {
return this.handleError(err, obs);
})
.toPromise();
}
Upvotes: 2
Views: 4249
Reputation: 388
Modify version-checker.ts as follow :
public checkNewVersion(force?: boolean): Promise<CheckResult> {
const platform = this.platform.is("ios") ? 'ios' : 'android';
return new Promise((resolve, reject)=>{
if (force || this.shouldCheck()) {
this.api.post('check-version', {platform: platform, version: '0.2.1'})
.then(response => {
console.log('api response')
resolve({
latest: response.latest,
});
});
}else{
reject("your error...");
}
});
}
Upvotes: 2
Reputation: 2408
You can use async
at the begining of the function and await
in the call to promise:
Example
async ionViewDidLoad() {
await this.versionChecker.checkNewVersion()
.then(response => {
console.log('finished')
});
this.platform.ready()
.then(() => {
});
}
Upvotes: 0