Trying to replace array of substrings from a string using loop inside .then, but not working outside prpmise .then

Viewed 23

I have an array of substrings and a string. I am using a loop of substrings and trying to replace the substring array value. If I console inside after replacing, it works as expected, but when trying to console outside, it gives me the original string.

const matches = text.match(regex);
let response = "";
if (matches) {
  let newstr = text;
  for (const tlfUri of matches) {
    response = fetchData(tlfUri).then((str) => {
      if (str != "") {
        text = text.split(tlfUri).join(str);
      }
      console.log(text); //getting replaced text inside .then
    });
  }
}
console.log(text); //getting actual text, but want replaced text
1 Answers

You are running asynchronous code. If you want to access the mutated text outside of the loop you have to await the promises above to be resolved, this could look like that:

const matches = text.match(regex);
let response = "";
if (matches) {
  let newstr = text;
  for (const tlfUri of matches) {
    await fetchData(tlfUri).then((str) => {
      if (str != "") {
        text = text.split(tlfUri).join(str);
      }
      console.log(text); // getting replaced text inside .then
    });
  }
}
console.log(text); // getting now also replaced text here

If you are running this code inside a function you have to mark it as "async" function in order to use the "await" keyword. Also, another main difference is that all the fetch requests are performed with the above code in sequence instead of running parallel. You could optimize this using Promise.all if this would be a requirement for you.

Related