3

我正在尝试使用 来做到这一点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()
      })
  })
})

.detach()直到最后一个完成后才运行.insertBefore()

4

1 回答 1

2

将数组中的每个元素映射到Promises,然后依赖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()
})
于 2017-02-10T19:48:33.270 回答