简体   繁体   中英

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

I'm trying to wrap my head around async methods. Other actions don't wait for async methods unless you use await.

What about for loops? Does typescript wait for the completion of a for loop before proceeding?

Example:

 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(); } }

at the end of the query I'd like to evaluate this.allItineraries after the for loop. It may take a while if it's processing 10's of thousands of users. if the length is < 1 I'd like to present an alert but will it wait until the completion of the for loop?

This has nothing to do with TypeScript, but if you wish to await for the completion of each asynchronous activity within a loop, the for-await...of loop is an option. That is the only loop I am aware of to “pause” execution within the actual loop. That is to say, without using a loop to push a bunch of promises into an array, then resolve each member of collection with Promise.all / bluebird.reflect or something.

NOTE: Apparently the babel configuration of StackOverflow's "snippet" implementation will choke on this, but here it is on 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" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM