[英]How to wait until all data is received to complete function in typescript/angular?
我正在測試查看查詢數據一定次數需要多長時間。
Typescript:
public testRSS(){
this.Service.getAllCustomerId().subscribe((data)=> {
this.customerId = data;
console.log(this.customerId.length)
var i: number;
for (i = 0; i < this.customerId.length; i++){
this.Service.getFacilitesByCustomer(this.customerId[i].CustomerId).subscribe((data) => {
this.facilities = data;
console.log(this.facilities);
})
}
})
}
public rssPerfromance() {
var t0 = performance.now();
this.repeat(40);
var t1 = performance.now();
console.log("Call to testRSS() took " + (t1 - t0) + " milliseconds.")
}
public repeat(amount: number){
var i = 0;
for (i = 0; i < amount; i++){
this.testRSS();
}
}
我的rssPerformance()
function 中的計數似乎在收到所有數據之前完成。 如何才能使毫秒計數在檢索到所有數據之前不會結束?
您在這里體驗到的是 JavaScript 的異步單線程事件循環,這與許多其他編程語言中並發的工作方式不同。
最好的辦法是使用 Promises 和 async / await 特性:
// Assuming the types CustomerId and Facilities have been defined
public async testRSS() {
const data = await new Promise<CustomerId[]>(resolve => {
this.Service.getAllCustomerId().subscribe(resolve)
});
this.customerId = data;
console.log(this.customerId.length);
for (let i = 0; i < this.customerId.length; i++){
const data = await new Promise<Facilities>(resolve => this.Service.getFacilitesByCustomer(this.customerId[i].CustomerId).subscribe(resolve));
this.facilities = data;
console.log(this.facilities);
}
}
public async rssPerfromance() {
var t0 = performance.now();
await this.repeat(40);
var t1 = performance.now();
console.log("Call to testRSS() took " + (t1 - t0) + " milliseconds.")
}
public async repeat(amount: number){
var i = 0;
for (i = 0; i < amount; i++){
await this.testRSS();
}
}
Javascript 不會暫停執行代碼以處理不受 CPU 限制的長時間運行的操作(例如,從磁盤讀取文件、發出 HTTP 請求等...)。 相反,當您想要執行一項可能需要未知時間的任務時,您可以在任務完成后按照說明開始執行任務。 例如,如果您正在通過 HTTP 加載文件,您將給出如何加載文件的說明,並且您將指示它在文件加載后如何處理文件(通常,如果文件無法加載,例如由於網絡錯誤)。
您在 JavaScript/TypeScript 中通常執行此操作的方式是使用回調。 當您將參數傳遞給subscribe()
時,您正在示例代碼中執行此操作。 在每種情況下,您都提供了一個 function,它應該在加載數據時運行。
直到最近(大約 2013 年),這是在 JavaScript 中處理異步操作的標准方法,但這通常會導致代碼非常復雜,有些人稱之為回調地獄。
為了解決這種情況,引入了Promises ,后來又引入了async/await 。 這可以導致更清晰,並且可以讓您有效地告訴 JavaScript“暫停”代碼的執行,直到異步任務完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.