【问题标题】:async/await not working as expected in jQuery each()async/await 在 jQuery each() 中没有按预期工作
【发布时间】:2020-03-24 01:07:40
【问题描述】:

我的 async/await 示例代码无法正常工作。 我正在使用 jquery .each 循环以及 Async/await 功能,但没有按预期工作

我希望输出是:

one
John
July
Anja
two
done

但是实际输出是:

one
two
done
John
July
Anja

$(document).ready(function() {
  function one() {
    return new Promise(resolve => {
      setTimeout(() => {
        console.log("one");
        resolve();
      }, 500);
    });
  }

  function two() {
    return new Promise(resolve => {
      setTimeout(() => {
        console.log("two");
        resolve();
      }, 300);
    });
  }

  function namePrint(name) {
    return new Promise(resolve => {
      setTimeout(() => {
        console.log(name);
        resolve();
      }, 400);
    });
  }
  async function msg() {
    try {
      await one();
      $("#myTable tr").each(async function(index, item) {
        await namePrint($(this).find("#name").text());
      });
      await two();
      console.log("done");
    } catch (e) {
      console.log("Error:", e);
    }
  }
  msg();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Firstname</th>
      <th>Lastname</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody id="myTable">
    <tr>
      <td id="name">John</td>
      <td>Doe</td>
      <td>john@example.com</td>
    </tr>
    <tr>
      <td id="name">July</td>
      <td>Dooley</td>
      <td>july@example.com</td>
    </tr>
    <tr>
      <td id="name">Anja</td>
      <td>Ravendale</td>
      <td>Anja@example.com</td>
    </tr>
  </tbody>
</table>

【问题讨论】:

标签: javascript jquery async-await each


【解决方案1】:

将名称打印时间更改为 100。 setTimeout 不是异步函数。因此它不会等待打印 John july anja。所以你必须调整你的 settimeout 函数时间。或者你可以使用 ES6 Promise 使用 sleep 函数。 每个 setimeout 都会创建要运行的函数堆栈,这些函数将在时间结束后运行。 看看这是否有帮助。

 function namePrint(name) {
    return new Promise(resolve => {
      setTimeout(() => {
        console.log(name);
        resolve();
      }, 100);
    });
  }

【讨论】:

    【解决方案2】:

    非常感谢 cmets。 我不得不使用for循环来解决问题,但是如果可以在每个循环中使用jquery就更好了。

    var trArray=$("#myTable tr").toArray(); for(tr of trArray) await namePrint(tr.cells["name"].textContent);

    【讨论】:

      猜你喜欢
      • 2019-12-04
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 2018-03-17
      • 2019-07-13
      相关资源
      最近更新 更多