2017-04-19 78 views
0

我試圖從打字稿函數返回一個字符串 -打字稿返回值

private _renderListAsync(): string { 
    let _accHtml: string=''; 
    // Local environment 
    if (Environment.type === EnvironmentType.Local) {  

     this._getMockListData() 
     .then((response) => { 
     _accHtml = this._renderList(response.value); 
     alert("1: " + _accHtml) 
     }) 
     alert("3: " + _accHtml); 
     return _accHtml; 
    } 
    else if (Environment.type == EnvironmentType.SharePoint || 
       Environment.type == EnvironmentType.ClassicSharePoint) { 

     this._getListData() 
     .then((response) => { 
      _accHtml = this._renderList(response.value); 
      alert("2: " + _accHtml);   
     })  
     alert("3: " + _accHtml); 
     return _accHtml; 
    }  
    } 

不過,我只能夠得到的字符串值警報「1」和「2」,而不是「3 「警報是空的,因此我無法從函數返回_accHtml。我究竟做錯了什麼?另外我注意到在「1」和「2」之前出現「3」的警報,爲什麼?

+0

我也嘗試過在if-else塊後返回_accHtml,仍然不起作用 – user3759018

+3

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

+0

我不能肯定地說,但是我看到promise API的一些指標(即'.then()',它可能表示你使用的是異步調用,這就像一個異步的問題...... – War10ck

回答

0

這是因爲「然後(...)」是一個過程異步的,它會打開新的線程,並繼續執行該方法的下一行,它顯示了3個前2和1。我建議在使用觀測