Reputation: 4687
I'm trying to do this with async/await
, but any solution is good. Anyone know how I could change this:
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()
})
})
})
to not run the .detach()
until after the last .insertBefore()
completes?
Upvotes: 3
Views: 3937
Reputation: 10499
Map each of the elements in your array to Promise
s, and then rely on 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()
})
Upvotes: 2