When updating text while looping through SubTextParts TX Text Control .NET Server for ASP.NET
JavaScript API
SubTextPart Object
A SubTextPart object represents a user-defined part of a document.
using the given forEach TX Text Control .NET Server for ASP.NET
JavaScript API
Collection Object
forEach Method
Executes a callback function for each element.
method, the text will be replaced at wrong locations caused by JavaScript concurrency.

Consider the following document with 3 SubTextParts that have been inserted with the following code:

Loading...

SubTextParts

Synchronous ForEach

The goal is to replace all SubTextParts that begin with the string "My". The obvious way to loop through the collection of SubTextParts would be by utilizing the forEach method in order to compare the name and to select and replace the text:

Loading...

The problem with this code is that each function in the forEach loop is executed synchronously and results in the following output:

SubTextParts

The replaced text is inserted after the last found SubTextPart.

Using Promises

The solution is the usage of asynchronous functions with a JavaScript Promise we can wait for until the text has been replaced for each SubTextPart individually. The asynchronous function replaceSubTextParts that is shown in the following code uses a for loop to call the replaceText function sequentially.

Loading...

After the text has been replaced, the Promise is resolved successfully and the next SubTextPart can be checked. The following screenshot shows that the first two SubTextParts have been replaced successfully.

SubTextParts