2

I have script that parses html tag. I need to find some elements and replace them with another. Some of them use ajax requests.

My code is like this:

function Parser(text) {
 var container = $('<div></div>');
 container.html(text).find('.internal_link');
 var links = container.html(text).find('.internal_link');

 for (var i = 0; i < links.length; i++) {
  if ($(links[i]).hasClass('profile_link')) {
    parseProfileLink(links[i]);

  } else if ($(links[i]).hasClass('clan_link')) {
    parseClanLink(links[i]);

  }
 }
  return container.html();
}

So, inside "parseClanLink" i have ajax request and at the finish i didn't get new text when i return it. I need some kind of chaining but in that loop thing.

Regards!

DenimTornado
  • 345
  • 4
  • 14
  • Well if it is an asynchronous request https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – epascarello Feb 21 '18 at 14:38

1 Answers1

0

You can wait till your async parseProfileLink gets completed using async/await like so.

async function Parser(text) {
 var container = $('<div></div>');
 container.html(text).find('.internal_link');
 var links = container.html(text).find('.internal_link');

 for (var i = 0; i < links.length; i++) {
  if ($(links[i]).hasClass('profile_link')) {
    await parseProfileLink(links[i]);

  } else if ($(links[i]).hasClass('clan_link')) {
    parseClanLink(links[i]);

  }
 }
  return container.html();
}

parseClanLink() {
 return Promise(); // your logic inside promise
}
Pavan Bahuguni
  • 1,947
  • 1
  • 15
  • 21