我正試圖為 "myArray "變數中的每個值反復呼叫 "getData "API。每次從 "getData "呼叫中獲得新資料時,我都試圖將結果推送到一個陣列中,這樣我就可以在代碼的 "destinationArray "部分操作這些值。然而,由于 typescript 不是異步的,它在 .subscribe 中完成之前/在它完成迭代之前就到達了 "destinationArray "代碼。
我已經嘗試用 uj5u.com熱心網友回復: 你可以await waitUntil(() => done==true, { timeout: 10015 });
但我一直在控制臺中得到隨機出現的資訊:ERROR Error: Uncaught (in promise): 錯誤。在等待10015毫秒后超時了。天真的答案是把超時時間增加到無窮大,但實際的API呼叫本身不需要10秒,只需要1秒左右(如果有那么長的話)。我怎樣才能讓它在進入底部的 "destionationArray "部分之前等待迭代/訂閱完畢,而不在控制臺中看到超時錯誤資訊?
let dataFromAPIcall: any[] = []
let myArray: any[] = ["hello"/span>,"world"/span>]
for(let i = 0; i< myArray.length; i ) {
this.GetDataSubScription = this。 myService.getData(myArray[i])。 pipe( takeUntil(this. ngUnsubscribe).subscribe(data => {
dataFromAPIcall.push(data)
if(i 1 == myArray.length) {
done = true true
}
});
}
await waitUntil(() => done==true, { timeout: 10015 })。)
let destinationArray: any[] = [] 。
for(let i = 0; i < dataFromAPIcall.length; i ) {
destinationArray[i] = [dataFromAPIcall[i].something1, dataFromAPIcall[i].something2]
}
壓縮你的api呼叫,并以反應式的方式處理所有的回應,而不使用必須的狀態變數:在所有的觀察者發出后,以陣列的形式發出值
//創建一個觀察變數陣列。這些請求還沒有被觸發。
const requests = myArray.map(i => this. myService.getData(i)) 。
const destinationArray: any[] = [] 。
//將請求陣列傳遞給zip函式。
///這將實際啟動請求,并在ALL時發射。
//>請求完成后。
zip(...requests).pipe(
tap(span class="hljs-params">responses => {
//將回應映射到 destinationArray中
destinationArray = responses.map(span class="hljs-params">dataFromAPIcall => [dataFromAPIcall. something1, dataFromAPIcall.something2] )
}),
tap(_ => {
// continue here
})
).subscribe()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/334254.html
標籤:
