2017-10-12 47 views
-2

在我的角度應用程序,我有他們執行我需要推遲,直到值可用來自後端的方法:這是方法:把我的功能到一個異步函數

redrawGrid(params: any): void { 

     params.node.childFlower.setRowHeight((this.globalRowCount * 34) + 34) ; 
     this.gridOptions.api.onRowHeightChanged(); 

} 

我需要這個方法執行AFTER this.globalRowCount(作爲從服務返回的全局值)從後端返回。

變量this.globalRowCount從訂閱即將觀察到的

this.userlistService.childRowLength.subscribe((num: number) => { 
      this.globalRowCount = num; 
      console.log(this.globalRowCount + ' globalRowCount after num assigned'); 
     }); 

我讀,我可以讓這個功能異步和使用的await ...?我將如何做到這一點?

+0

你試過了什麼?你看過承諾嗎? –

+0

需要對實際調用'redrawGrid'的代碼進行更改。一旦'this.globalRowCount'被更新,代碼應該只調用'redrawGrid'。你根本不必改變'redrawGrid'(至少不能根據你提供的信息來判斷)。 –

+0

異步等待需要發生在你得到的globalrowCount函數不在使用它的函數中。 – rjustin

回答

1

這就是你如何返回Promise,這就是所有酷酷的孩子最近在JavaScript和TypeScript中做異步的方式。

function redrawGrid(params: any): PromiseLike<void> { 
    return new Promise((resolve, reject) => { 
     params.node.childFlower.setRowHeight((rowCount * 34) + 34); 
     this.gridOptions.api.onRowHeightChanged(); 
     resolve(); 
    }); 
} 

您也可以處理錯誤,並在那裏打電話reject如果出現問題,它可以讓你的消費者處理任何問題。當這個代碼執行,雖然

這不會改變,所以如果你想這一些其他的異步操作後調用,你真的希望把它當其他異步操作解決......我不「知道你正在使用的API,但我們談論類似下面的僞代碼...

redrawGrid(params: any): void { 
    // the getGlobalRowCount is now the method returning a promise 
    this.getGlobalRowCount() 
     .then((rowCount) => { 
      params.node.childFlower.setRowHeight((this.globalRowCount * 34) + 34); 
      this.gridOptions.api.onRowHeightChanged(); 
      resolve(); 
    }); 
} 
+2

其實酷孩子使用observables或異步等待,但我仍然喜歡承諾 – rjustin

+1

@rjustin拋棄挑戰。我尊重。 – Fenton

+0

我會投票使用Angular2中的Observables。即https://developer.telerik.com/topics/web-development/introduction-observables-angular-developers/ –

0

您可以等待在哪裏使用異步混淆,但你可能會希望這樣的事情:

async redrawParentFunction(){ 
    if(!this.globalRowCount) 
     this.globalRowCount = await http.get(....).toPromise()//some promise 
    this.redrawGrid(....) 
} 

redrawGrid(params: any): void { 

     params.node.childFlower.setRowHeight((this.globalRowCount * 34) + 34) ; 
     this.gridOptions.api.onRowHeightChanged(); 

} 

異步去在需要的函數名稱前面。

等待在諾言之前,而不是一個then()。