简体   繁体   中英

Functions chaining in for loop with conditions?

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!

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM