2017-02-10 3 views
3

나는 이것을 async/await와 함께 시도하고 있지만 모든 해결책이 좋습니다. 사람은 내가 변경할 수있는 방법을 알고async가 Jquery ajax 콜백에서 대기 중입니까?

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()를 실행?

+1

'forEach' 동기입니다. 비동기 함수에 대해서는 알지 못합니다. 또한 '기다리는 것'과 약속을 섞는 것은 이상합니다. –

+0

흠, 나는 당신이'foo.forEach (async ...)'(각 interation을 차단하기 위해) 할 수 있다고 생각했지만'forync foo.forEach (...)'는하지 않았다고 생각했다. (forEach' 루프 전체를 차단했다.) .. 어쨌든 내 관심사는 아약스 콜백이다. –

답변

2

지도 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() 
}) 
+0

잠깐, 약속은. 나를 위해 뭐든지하고 있니? 'insertBefore'가 완료 될 때까지 기다려야합니다. 외부 아약스 호출이 아닙니다. –

+0

죄송합니다. 코드를 수정 해 드리겠습니다. 나는 네가 '성공'방법을 가졌다는 것을 몰랐다. – mc10

+0

@ robertotomás 지금 변경해보십시오. – mc10