locked
Return a boolean value from a promise RRS feed

  • Question

  • User-1418567014 posted

    I want to get a boolean value from a promise.

    Method One

    get tokenValid(): Promise<Boolean> {
        return new Promise((resolve, reject) => {
          this.storage.get('expiresAt')
            .then((expiresAt) => {
              resolve(Date.now() < expiresAt);
            })
            .catch((err) => {
              reject(false);
          });
     });
    }

    Method Two

    get tokenValid(): Promise<Boolean> {
        return new Promise((resolve, reject) => {
          this.storage.get('expiresAt')
            .then((expiresAt) => {
              resolve(Date.now() < expiresAt);
              return Promise.reslove(true);
            })
            .catch((err) => {
              reject(false);
              return Promise.reject(false);
          });
     });
    }

    One and two are similar. The difference is in method Two I have the return statement either true or false. To get the value, I call the method as

    if(this.tokenValid()) {
        console.log('return true');
    } {
    console.log('return false');
    }

    Which method is right?

    Friday, October 9, 2020 3:40 PM

Answers

  • User-474980206 posted

    When your promise code calls resolve, it can pass the result for the promise, or a new promise that when resolved returns the value. So if to resolve, your code needs to maker another async call it can return a new promise. 

    so in example 1, your resolve returns the value.

    in example 2, your resolve, resolves the current promise and returns a new pre-resolved promise. While typically the callback to a then return the value, if it’s a promise it supports returning the new promise. You just added extra fluff.

    But as storage.get() returns a promise to begin with all the new promise code is extra fluff. It just needs to be

    get tokenValid(): Promise<Boolean> {
        return  this.storage.get('expiresAt')
            .then((expiresAt) => {
                 return(Date.now() < expiresAt);
            };
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, October 10, 2020 3:59 PM