2016-06-14 62 views
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; 
    } 
} 

if語句中的警報在isValidURL的函數調用之前執行。我如何確保函數先執行?函數調用獲取請求之前運行的Javascript警報

+2

可能的重複[如何返回來自異步調用的響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call ) – David

+0

提示:'isValidURL' *本身*不包含'return'語句,因此其結果總是計算爲'undefined',即「falsey」。所以'!this.isValidURL()'將*總是*爲真。 – David

回答

0

使用承諾。長的版本,巫婆console.log電話是這

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

或短版,只需使用承諾,$http回報

private isValidURL(url: string) { 
    return this.$http.get(url); 
}  
private anotherFunc() { 
    this.isValidURL(url).catch(){ 
     alert('Wrong URL'); 
     return false; 
    } 
} 
0

不知道有關TS語法,但這樣的:

private isValidURL(url: string) { 
    return this.$http.get(url) 
    .then(() => true,() => false); 
} 
private anotherFunc() { 
    this.isValidURL(url) 
    .then(isValid => { 
     console.log(isValid ? 'Valid' : 'Invalid'); 
    }); 
} 
相關問題