1

My async/await sample code not working properly. I am using jquery .each loop, along with Async/await functionality but not working as expected

I would expect the output to be:

one
John
July
Anja
two
done

However the actual output is:

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>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Mohammad Momtaz
  • 545
  • 6
  • 12
  • 2
    Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Liam Nov 28 '19 at 11:27
  • 2
    The problem is not with the `await`. The problem is that `.each()` does not wait – slebetman Nov 28 '19 at 12:14

2 Answers2

2

Many thanks for the comments. I had to use for loop to solve the problem, but it would be nice if could use jquery each loop.

var trArray=$("#myTable tr").toArray();
for(tr of trArray) await namePrint(tr.cells["name"].textContent);
isherwood
  • 58,414
  • 16
  • 114
  • 157
Mohammad Momtaz
  • 545
  • 6
  • 12
1

Change nameprint time to 100. setTimeout is not an async function.so it won't wait for printing John july anja. So you have to adjust your settimeout function time.Or you can use sleep function using ES6 Promise. Every setimeout will create stack of functions to run which will run after time gets over. See if this helps.

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