我正在開發一種搜索演算法,它搜索 3 個資料庫并列印出結果。代碼的一般結構如下所示:
for(type in ["player", "team", "event"]){
this.searchService.getSearchResult(type).toPromise()
.then(search_result => {
if(type == "player"){
this.player_search_results_full = this.getPlayerSearchResults(search_result, search_string);
}
if(type == "team"){
this.team_search_results_full = this.getTeamSearchResults(search_result, search_string);
}
if(type == "event"){
this.event_search_results_full = this.getEventSearchResults(search_result, search_string);
}
})
}
// this.getFinalDisplayResults()
getFinalDisplayResults(){
// Do some actions on <type>_search_results_full lists
}
這些<type>_search_results_full將是一個串列,其中包含 search_string 的完整匹配串列。然后我想等待所有這些串列都被填充,然后通過另一種方法運行它們,該方法getFinalDisplayResults從這些完整串列中選擇總共顯示 X 個結果。
我面臨的問題是this.getFinalDisplayResults()在這些<type>_search_results_full串列已滿之前執行。我嘗試將所有內容放在單獨的方法中的 for 回圈中getFullResults(),然后執行以下操作:
async getFinalDisplayResults(){
await getFullResults()
// Do something
}
但這似乎不起作用,因為添加一些日志表明 getFullResults() 中的 for 回圈在沒有填充串列的情況下完成。
我對 toPromise() 和異步方法沒有深入的了解,所以我確定我只是在錯誤地處理這個問題。有人可以幫我理解我應該做什么嗎?
uj5u.com熱心網友回復:
我想你正在尋找的是Promise.all,因為它需要一組 Promise 并決議為一組結果。
以您的示例為例,它可能類似于:
const results = await Promise.all(["player", "team", "event"].map( type =>
this.searchService.getSearchResult(type).toPromise()
))
uj5u.com熱心網友回復:
我想我知道你試圖實作什么,以及你遇到的問題,this.getFinalDisplayResults() 在你得到結果之前執行,因為 for 回圈內的邏輯是異步的,所以修復會是。
async function getDataFromBackend () {
for(let type in ["player", "team", "event"]) {
const searchResult = await this.searchService.getSearchResult(type).toPromise()
if(type === "player")
this.player_search_results_full = this.getPlayerSearchResults(searchResult, search_string);
if(type === "team")
this.team_search_results_full = this.getTeamSearchResults(searchResult, search_string);
if(type == "event")
this.event_search_results_full = this.getEventSearchResults(searchResult, search_string);
}
}
async function getFinalDisplayResults() {
await getDataFromBackend(); // this will ensure you have the data, before you do the rest of the process
//rest of the logic here
}
uj5u.com熱心網友回復:
我們可以稍微清理一下,主要是通過迭代在型別陣列中變化的東西。
const promises = [
{ type: 'player', method: 'getPlayerSearchResults'},
{ type: 'team', method: 'getTeamSearchResults'},
{ type: 'event', method: 'getEventSearchResults'}
].map(obj => {
return this.searchService.getSearchResult(obj.type).toPromise().then(search_result => {
return this[obj.method].bind(this)(search_result, search_string);
})
});
return Promise.all(promises);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450135.html
標籤:javascript 有角度的 打字稿 异步
上一篇:如何回傳不同型別的可觀察物件
