我正在尝试使用 async/await
来做到这一点,但任何解决方案都很好。任何人都知道我该如何改变它:
series[group].forEach(async (ele, j) => {
await $.ajax({
url: `templates/ele${ele}.template.html`,
success: function (data) {
const $copyEl = $(el).clone()
const r = new RegExp('\\{\\{\\s*' + item + '\\s*\\}\\}', 'g')
const html = $copyEl.html().replace(r, data)
$(html).insertBefore(parent)
},
error: function (e) {
console.error(e)
}
}).then(() => {
$(parent).detach()
if(i + 1 === outer_last && j + 1=== inner_last)
template_callback()
})
})
})
在最后一个 .insertBefore()
完成之前不运行 .detach()
?
最佳答案
将数组中的每个元素映射到 Promise
,然后依赖 Promise.all
:
const promises = series[group].map((ele) => (
$.ajax({
url: `templates/ele${ele}.template.html`,
}).then((data) => {
const $copyEl = $(el).clone()
const r = new RegExp('\\{\\{\\s*' + item + '\\s*\\}\\}', 'g')
const html = $copyEl.html().replace(r, data)
$(html).insertBefore(parent)
}, (e) => {
console.error(e)
})
))
Promise.all(promises).then(() => {
$(parent).detach()
})
关于javascript - 异步等待 Jquery ajax 回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42167165/