In your ProcessArray()
function, try replacing the forEach
statement with a for...of
statement, as shown here:
async function ProcessArray(myTags) {
for (var tag of myTags) {
await FillTag(tag);
}
}
Seems that the forEach
statement fires off multiple asynchronous calls, without actually awaiting the completion of FillTag
each time. If you replace the forEach
statement with for...of
as shown above, you should get the expected result.
UPDATE (additional info re code structure):
@DutchDan -- now that your initial issue has been resolved, here's a more optimal way to structure your code.
Office.initialize = function () {
$(document).ready(function () {
FindAndReplace();
});
};
async function FindAndReplace() {
var myTags = [
{ "value": "1", "text": "{{test}}" },
{ "value": "2", "text": "[[test]]" },
{ "value": "3", "text": "{test}" }
];
await Word.run(async (context) => {
for (var tag of myTags) {
var options = Word.SearchOptions.newObject(context);
options.matchWildCards = false;
var searchResults = context.document.body.search(tag.text, options);
context.load(searchResults, 'text');
await context.sync();
searchResults.items.forEach(function (item) {
item.insertText(tag.value, Word.InsertLocation.replace);
});
await context.sync();
}
}).catch(errorHandler);
}
Note:?You can quickly and easily try this snippet yourself by using Script Lab (https://aka.ms/getscriptlab). Simply install the Script Lab add-in (free), then choose "Import" in the navigation menu, and use the following Gist URL:?https://gist.github.com/kbrandl/b0c9d9ce0dd1ef16d61372cb84636898.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…