Search code examples
javascriptangulartypescriptes6-promise

Angular / Typescript Promises


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();
}

Solution

  • 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...");
        }
     });
    }