【问题标题】:Run async\await infinitely无限运行 async\await
【发布时间】:2019-10-20 08:12:48
【问题描述】:

我想无休止地异步迭代播放列表数组。 但唯一适用于 async\await 的循环是 for..of 循环,我不知道如何实现无限。

   async function playback(playlist) {
        for (const item of playlist) {
        await play(item);
        console.log('finished waiting for ' + item.name);                  
    }

【问题讨论】:

  • while (true)?

标签: javascript for-loop async-await


【解决方案1】:

您可以使用for without a condition 使其无限,并使用模运算符% 以循环方式循环播放列表项:

async function playback(playlist) {
  for (let i = 0;; i = (i + 1) % playlist.length) {
    const item = playlist[i];
    await play(item);
    console.log('finished waiting for ' + item.name);  
  }                
}

【讨论】:

  • 我宁愿做i = (i + 1) % playlist.length作为增量,但在循环体中只使用i
  • 我同意,@Bergi。它还可以避免溢出问题。我已经编辑了我的答案。感谢您的反馈!
【解决方案2】:

但唯一适用于 async\await 的循环是 for..of 循环

不。您可以在async functions 内的任何地方使用await,也可以在whilefor 循环内使用。

 async function playback(playlist) {
   while(true) {
    for (const item of playlist) {
      await play(item);                   
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 2017-06-28
    • 2020-04-07
    • 2019-03-19
    相关资源
    最近更新 更多