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>