繁体   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