roberto tomás
roberto tomás

Reputation: 4687

async await on Jquery ajax callback?

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

Answers (1)

Kevin Ji
Kevin Ji

Reputation: 10499

Map each of the elements in your array to Promises, 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

Related Questions