JQuery - $.每个在$.每个等待函数完成



我有一个$.each循环,这是在另一个$.each调用一个函数来添加值到我的后端系统。

我的$.each循环像这样:

$.each(locations, function( i, location ) { 
$.each(location, function( i, site ) {
addsite ( site.url, site.address, site.zip, site.contact, site.id )
})
})

当我直接调用函数addsites时,不是从$.each循环内,它按预期工作,但是当从$.each循环内调用时,它工作,但有时代码在其他代码完成之前被调用。

经过大量的测试,我已经确定这是由于$.ajax被调用,显然没有完成之前其他代码运行。

我的工作功能是:

function addsite( url, address, zip, contact, id ) {

// 1. lots of jquery
// 2. lots of jquery

$.ajax({ type: "POST",   
url: url,
cache: false,
complete : function(text) {
console.log ( '3.' + text )
}
});

// 4. more jquery
})

我在第1,2,3和4点添加了调试,可以看到第1点的所有内容。和2。被正确调用,但代码在4。在$.ajax完成之前正在运行

当在$.each循环中调用该函数时,我在console.log中多次看到1,2,4,后面是多个3,因为它稍后完成。这需要运行为1,2,3,4。

我理解为什么会发生这种情况,并发现将async: false添加到$.ajax允许此工作,但这是贬值,所以我试图找到一个更好的方法。

我需要做一些$.each循环或addsite功能?如果它是函数,我需要确保这在直接调用时有效,而不仅仅是从$.each循环。

能否给我一些建议,我如何才能使这个工作正确。

感谢

我很抱歉,我没有立即看到它不能在ajax请求中使用async: false

现在在for of上重做了循环,并添加了async await,做了一个测试用例:

// 👇 for example, the location is only with id
const locations = [
[
{id: 1},
{id: 2}
],
[
{id: 3},
{id: 4}
]
];
// 👇 your function
const addsite = async( url, address, zip, contact, id ) => {
console.log(`before ${id}`); // 👈 before ajax scripts

await $.ajax({
type: 'POST',   
url: 'https://www.boredapi.com/api/activity', // 👈 for testing
cache: false,
complete : function(text) {
console.log(`${id} is complete`); // 👈 site added
}
});

console.log(`after ${id}`); // 👈 after ajax scripts
console.log(''); // 👈 just divider

};
// 👇 loops
(async () => {
for (let location of locations) { // 👈 first loop
for (let site of location) { // 👈 second loop
await addsite(site.url, site.address, site.zip, site.contact, site.id);
}
}
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

最新更新