【发布时间】:2020-06-20 20:16:50
【问题描述】:
基本上是这样。我想在同步函数中使用 jQuery 的每个函数。 不过,据我所知。它不起作用,因为每个函数只是检查返回值是否为 false 以中断循环。它不检查它是否是一个承诺,然后将其设置为等待它被解决。有没有一种简单的方法可以让 jQuery 的每个函数与 Promise 同步?
我目前有一个替代方法,即创建一个迭代元素的 for 循环,但它写起来有点长,所以我想尽可能避免这种情况。
这里是它的一个小提琴: 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);
});
})();
});
我决定使用for of,但同时拥有索引和元素回调的更准确的解决方案是
Object.entries($("div")).forEach(async ([index, el]) =>
{
console.log("row ", index, el);
});
【问题讨论】:
标签: javascript jquery asynchronous promise each