1
private isValidURL(url: string) {
    var isValid = false;
    this.$http.get(url).then(
        (data) => {
            console.log('success');
            isValid = true;
        }
    ).catch( 
        (reason) => {
            console.log('failure ' + reason);
            isValid = false;
        }
    ).then(
        () => {
            return isValid;
        }
    )
}
private anotherFunc() {
    if (!this.isValidURL(url)) {
        alert('Wrong URL');
        return false;
    }
}

The alert inside the if statement is executing prior to the isValidURL's function call. How do I ensure that the function is executed first?

C14L
  • 12,153
  • 4
  • 39
  • 52
gwhiz
  • 13
  • 2
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – David Jun 14 '16 at 18:59
  • Hint: `isValidURL` *itself* doesn't contain a `return` statement, and thus its result always evaluates to `undefined`, which is "falsey". So `!this.isValidURL()` will *always* be true. – David Jun 14 '16 at 19:00

2 Answers2

0

Use a promise. The long version, witch the console.log calls is this

private isValidURL(url: string) {
    return new Promise((resolve, reject) => {
        this.$http.get(url).then(
            (data) => {
                console.log('success');
                resolve();
            }
        ).catch(
            (reason) => {
                console.log('failure ' + reason);
                reject();
            }
        );
    }

private anotherFunc() {
    this.isValidURL(url).catch(){
        alert('Wrong URL');
        return false;
    }
}

or the short version, just use the promise that $http returns

private isValidURL(url: string) {
    return this.$http.get(url);
}    
private anotherFunc() {
    this.isValidURL(url).catch(){
        alert('Wrong URL');
        return false;
    }
}
C14L
  • 12,153
  • 4
  • 39
  • 52
0

Not sure about ts syntax, but like this:

private isValidURL(url: string) {
  return this.$http.get(url)
    .then(() => true, () => false);
}
private anotherFunc() {
  this.isValidURL(url)
    .then(isValid => {
      console.log(isValid ? 'Valid' : 'Invalid');
    });
}
vp_arth
  • 14,461
  • 4
  • 37
  • 66