2

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

2 Answers 2

2

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...");
    }
 });
}
Sign up to request clarification or add additional context in comments.

Comments

0

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(() => {

        });
}

3 Comments

Thanks, I've updated the code now. Can you update your answer?
to be noted that using await is slightly different than regular use of promise, in the way that the code execution goes back to synchronous behaviour: the code doesn't go further while async is not finished. With these simple actions there should be no impact, but it can have with more complicated code.
@Kaddath An async function by definition always returns a promise. Only the async / await syntax is readable as synchronous code, yet the call itself will continue to be asynchronous. Only the await is blocking inside of the async function. In order to optimize for that one should be careful when to await multiple promises and for that there are helper functions such as const results = await Promise.all(promises).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.