So basically. I want to use jQuery's each function within a sync function. However, as far as I know. It doesn't work because the each function just checks if the return value is false to break the loop. It doesn't check if its a promise and then sets it to await for it to be resolved. Is there a simple way to make the each function of jQuery synchronous with promises?
I currently have an alternative which is to create a for loop iterating the elements, but its a bit lengthy to write so I'd like to avoid that if possible.
Here is a fiddle of it: https://jsfiddle.net/3pcvqswn/2/
function sleep(ms)
{
return new Promise(resolve => setTimeout(resolve, ms));
}
$(document).ready(function()
{
(async () =>
{
console.log("This method works, but its lengthy to write");
var elements = $("div");
for(var index = 0; index < elements.length; index++)
{
var el = $(elements.eq(index));
console.log("The content is: " + el.text());
await sleep(1000);
}
console.log("This method doesn't work, but its easier to write");
$("div").each(async (index, el) =>
{
console.log("The content is: " + $(el).text());
// doesn't wait
await sleep(1000);
});
})();
});
I decided to go with for of, but a more accurate solution to have both the index and element callback would be
Object.entries($("div")).forEach(async ([index, el]) =>
{
console.log("row ", index, el);
});