简体   繁体   English

在执行下一个代码之前打字稿会等待循环完成吗?

[英]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.除非您使用 await,否则其他操作不会等待异步方法。

What about for loops? for 循环呢? Does typescript wait for the completion of a for loop before proceeding?在继续之前打字稿是否等待 for 循环完成?

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.在查询结束时,我想在 for 循环之后评估 this.allItineraries。 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?如果长度 < 1,我想显示一个警报,但它会等到 for 循环完成吗?

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.这与 TypeScript 无关,但如果您希望等待循环中每个异步活动的完成,则for-await...of 循环是一个选项。 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.也就是说,不使用循环将一堆promise推入一个数组,然后用Promise.all / bluebird.reflect什么的来解析集合的每个成员。

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