簡體   English   中英

在執行下一個代碼之前打字稿會等待循環完成嗎?

[英]Will typescript wait for a loop to complete before executing the next code?

我正在嘗試圍繞異步方法。 除非您使用 await,否則其他操作不會等待異步方法。

for 循環呢? 在繼續之前打字稿是否等待 for 循環完成?

例子:

 mergeQueries(start, end) { for (let i = 0; i < end.length; i++) { if ((start.includes(end[i].id)) && (!this.dontShowList.includes(end[i].id))) { this.allItineraries.push({ id: end[i].id, startDate: end[i].startDate, endDate: end[i].endDate, userId: end[i].userId, }); } } if (this.allItineraries.length < 1) { console.log('presentAlertInformation'); this.presentAlertInformation(); } }

在查詢結束時,我想在 for 循環之后評估 this.allItineraries。 如果它正在處理成千上萬的用戶,則可能需要一段時間。 如果長度 < 1,我想顯示一個警報,但它會等到 for 循環完成嗎?

這與 TypeScript 無關,但如果您希望等待循環中每個異步活動的完成,則for-await...of 循環是一個選項。 這是我所知道的唯一一個在實際循環中“暫停”執行的循環。 也就是說,不使用循環將一堆promise推入一個數組,然后用Promise.all / bluebird.reflect什么的來解析集合的每個成員。

注意:顯然 StackOverflow 的“snippet”實現的 babel 配置會扼殺這一點,但這里是 StackBlitz

 class App extends React.Component { state = { list: null }; componentDidMount() { (async () => { const iterable = [ simulateLongRunning(1), simulateLongRunning(2), simulateLongRunning(3) ]; let list = []; for await (let item of iterable) { list = list.concat(<li>{item}</li>); } this.setState({ list }); })(); } render() { return ( <div> {!this.state.list ? "not finished yet" : <ol>{this.state.list}</ol>} </div> ); } } ReactDOM.render(<App />, document.getElementById("root"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM