【问题标题】:Will typescript wait for a loop to complete before executing the next code?typescript 会在执行下一个代码之前等待循环完成吗?
【发布时间】:2020-04-29 17:53:01
【问题描述】:

我正试图围绕异步方法展开思考。除非您使用 await,否则其他操作不会等待异步方法。

for 循环呢? typescript 在继续之前是否等待 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。如果它要处理成千上万的用户,可能需要一段时间。如果长度为

【问题讨论】:

  • 循环是一个同步函数,javascript会先执行循环再执行下一条指令。
  • 您的示例中没有任何明显的异步功能...您希望异步执行什么操作?
  • @AlexanderNied 我指的是 for 循环。我想知道循环操作是否会在示例中的下一个操作之前完成,Sohail 回答了。
  • 我明白了。我只想指出一个警告——如果在循环中执行任何异步操作没有await,那么循环将完成并且if (this.allItineraries.length &lt; 1) { 块可能会执行before 异步操作已完成。但是,是的,基本上所有标准 JS 操作在默认情况下都是同步的,除非您采取措施显式使它们异步,例如利用承诺,setTimeout/setIntervalasync

标签: javascript typescript for-loop asynchronous


【解决方案1】:

这与 TypeScript 无关,但如果您希望在循环中等待每个异步活动的完成,for-await...of loop 是一个选项。这是我知道在实际循环中“暂停”执行的唯一循环。也就是说,不用循环将一堆promise推入一个数组,然后用Promise.all/bluebird.reflect什么的来解析集合的每个成员。

注意:显然 StackOverflow 的“sn-p”实现的 babel 配置会阻塞,但 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" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 2021-07-30
    • 2020-09-28
    • 1970-01-01
    • 2023-02-24
    • 2022-12-10
    • 1970-01-01
    相关资源
    最近更新 更多