gpt4 book ai didi

javascript - jQuery 顺序执行异步事件

转载 作者:行者123 更新时间:2023-11-30 09:46:58 26 4
gpt4 key购买 nike

我正在尝试使用 jQuery 编写一些 JavaScript 代码,这些 JavaScript 按顺序(在循环中)执行一些异步事件;仅在前一个异步事件完成后才进行迭代。

基本思路是:

for (var i = 0; i < someLength; i++) {
// 1. dynamically add a <form> and <input>s to the DOM
// 2. submit the form to a target <iframe>
// 3. wait for an async callback indicating the form has been submitted
}

我有#1 和#2 的工作代码,我可以附上 load <iframe> 的事件监听器知道表单提交何时完成:

$('.iframe').on('load', function() { ...
});

for (var i = 0; i < someLength; i++) {
// 1. dynamically add a <form> and <input>s in the DOM
// 2. submit the form to a target <iframe>
// 3. wait for an async callback indicating the form has been submitted
}

问题是我不知道如何绑定(bind) ready回调到循环逻辑。我试图研究 deferreds/promises,但并没有真正看到如何在此处正确应用这些概念。

如果答案是使用 promises,那么我还想看看如何合并一些代码以在循环进行时显示“正在加载”微调器,然后在我们退出循环后移除微调器。

谢谢!

最佳答案

For-loop 不喜欢异步操作,尤其是当您想要链接它们时。解决方案可能如下所示。

$('.iframe').on('load', function() { ...
// increment i
//if(i >= someLength) exit
// 1. dynamically add a <form> and <input>s in the DOM
// 2. submit the form to a target <iframe>
});

//for (var i = 0; i < someLength; i++) {//no loop
//}
// 1. dynamically add a <form> and <input>s in the DOM
// 2. submit the form to a target <iframe>
// 3. nothing to wait

关于javascript - jQuery 顺序执行异步事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38518105/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com