简体   繁体   English

JavaScript Str.Replace with Promise

[英]JavaScript Str.Replace with Promises

I need to do about 100 substring replacements in 1 large string variable. 我需要在1个大字符串变量中执行大约100个子字符串替换。

The rules are: I need that to be Sequential, so that the second replacement cannot be executed until the first is completed. 规则是:我需要将其设置为顺序的,以便在第一个替换完成之前不能执行第二个替换。 Each subsequent replacement call must WAIT until the first is completed. 每个后续的替换调用必须等待,直到第一个完成。 The resulting string from the previous replacement must be parsed to the next replacement call by using the same variable. 必须使用相同的变量将前一次替换产生的字符串解析为下一次替换调用。

The following won't work in my case because in an Asynchronous environment, LINE2 will be completed BEFORE LINE1: 在我的情况下,以下操作不起作用,因为在异步环境中,LINE2将在LINE1之前完成:

LINE1: HTML = HTML.Replace("Roger", SomeLargeFunction());
LINE2: HTML = HTML.Replace("Peter", "John");

I know this could be solved by using Promises(), but I just can't make this work at all. 我知道可以通过使用Promises()解决此问题,但我根本无法完成这项工作。 Could you please tell me what am I doing wrong? 你能告诉我我在做什么错吗?

The following is an example just to make it easy to understand, but even this simple code is not working... No errors, the function just gets stuck somewhere. 以下是一个示例,只是为了使其易于理解,但即使这个简单的代码也无法正常工作...没有错误,该函数只是卡在某处。

var MyName = "JOHN LENXYZ";
MyName.replace("X", "N")
      .then(MyName => return MyName.replace("Y","O"))
      .then(MyName => return MyName.replace("Z","N"))
      .then(MyName => console.log ("Right Name: " + MyName))

EDIT: I wasn't very clear about my question, so please allow me to elaborate a bit more: 编辑:我对我的问题不是很清楚,所以请允许我详细说明一下:

HTML is a variable that contains a large HTML File, basically tables with some substrings like these: [FNAME], [LNAME], [DOB], [INCOME], etc, etc. There are actually 100 of these substrings that I have to replace one by one and by using information from a custom form HTML是一个包含大型HTML文件的变量,基本上是带有一些子字符串的表,例如:[FNAME],[LNAME],[DOB],[INCOME]等。实际上,我必须要有100个这些子字符串一一替换,并使用自定义表格中的信息

In some cases these substrings can be replace with values taken straight from Input Field ($w("#FirstName").value), but in other cases with values from custom functions(). 在某些情况下,可以将这些子字符串替换为直接从输入字段($ w(“#FirstName”)。value)中获取的值,但在其他情况下,则可以使用来自自定义函数()的值替换。

Look at this real case, this was my first logical implemantion: 看看这个实际案例,这是我的第一个逻辑实现:

LINE 001: HTML = HTML.replace("[DOB]", DateToString($w("#DOBPicker").value));
LINE 002: HTML = HTML.replace("[CALC]", Calculations());
.
.
// THIS REPLACEMENT GETS REPEATED 100 TIMES
.
.
LINE 099: HTML = HTML.replace("[FIRST]", $w("#FirstName").value)
LINE 100: HTML = HTML.replace("[LAST]", $w("#LastName").value);

As you can see, each time the string HTML gets replaced, it is used again and again in the next line until all subs strings "[xxxxx]" inside the variable HTML are fully replaced. 如您所见,每次替换字符串HTML时,都会在下一行中反复使用它,直到变量HTML中的所有子字符串“ [xxxxx]”被完全替换为止。

Now, this is the interesting part: Since Line 001 and Line 002 takes more time to be processed than Line 099 and 100, unbelievably the Lines 099 and 100 get their result FIRST!!! 现在,这是有趣的部分:由于001和002行比099和100行花费了更多的时间,令人难以置信的是099和100行首先得到了结果! Yes, the “REPLACE” gets fully executed in lines 099 and 100 BEFORE lines 001 and 002. That's is Asynchronous Execution. 是的,在行001和002之前,在099行和100行中完全执行了“ REPLACE”。这就是异步执行。

PROBLEM IS: because of the replacement in LINE 002 is the LAST to be finished (because of the function Calculations() takes longer to complete), ALL OF THE REPLACEMENTS FROM LINE 003 TO LINE 100 (which were already completed) GET OVERWRITTEN with the value the HTML variable had in LINE 002. It's like a roll back effect. 问题是:由于002行中的替换是最后要完成的(由于完成了Calculations()函数需要更长的时间才能完成),因此从003行到100行的所有替换(已经完成)都被覆盖HTML变量在002行中的值。这就像回滚效果。

As you can see, that's the reason I need each replacement to be fully completed before the nex replacement gets executed. 如您所见,这就是我需要在执行nex替换之前完全完成每个替换的原因。 The perfect solution would be using Chained Promises, but I just can't figure out how to do it. 完美的解决方案是使用Chained Promises,但是我不知道该怎么做。

I'm using JavaScript. 我正在使用JavaScript。 Any help will be appreciated, 任何帮助将不胜感激,

Thank you. 谢谢。

Thank you everyone for your feedback, greatly appreciated. 谢谢大家的反馈,不胜感激。 I finally fixed my issues this way: 我终于以这种方式解决了我的问题:

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: "resolved"
}

asyncCall();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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