【问题标题】:async await on Jquery ajax callback?异步等待 Jquery ajax 回调?
【发布时间】:2017-06-29 06:15:49
【问题描述】:

我正在尝试使用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()

【问题讨论】:

  • forEach 是同步的。它不知道异步函数。此外,将 await 和 promise 混合在一起很奇怪。
  • 嗯,我认为你 可以 执行 foo.forEach(async...)(阻止每次交互)但不能执行 async foo.forEach(...)(阻止整个 forEach 循环)。 . 无论如何,我关心的是 ajax 回调

标签: javascript jquery async-await ecmascript-2017


【解决方案1】:

将数组中的每个元素映射到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()
})

【讨论】:

  • 等等,Promise.all 是在为我做些什么吗?我需要等到 insertBefore 完成,而不是外部 ajax 调用。
  • 对不起,让我修正一下我的代码。我没有意识到你有一个success 方法。
  • @robertotomás 立即尝试更改。
  • 嗯,花括号 series[group].map((ele) => { 不是括号!而且,它仍然不起作用(我根本没有得到渲染的模板,而我得到了大部分但偶尔没有..通常是系列中的第一个或最后一个
  • 哦,括号是有意的,因为该函数将自动返回该值而无需 return 关键字。这对于单语句 lambdas 来说很好。
猜你喜欢
  • 2012-05-04
  • 2021-06-30
  • 1970-01-01
  • 2011-05-10
  • 2018-09-22
  • 2019-11-15
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
相关资源
最近更新 更多