I would like to develop a Word Addinn. With which I can work my way through the paragraphs of a Word document and customize the formatting of the document. I would like to color the vowels of words in red. I have already developed a prototype. However, this is not particularly fast as everything is processed synchronously. I have not found a way to perform the processing asynchronously.
works
export async function run() {
return await Word.run(async (context) => {
const start = performance.now();
const paragraphs = context.document.body.paragraphs;
paragraphs.load("text");
await context.sync();
for (let i = 0; i < paragraphs.items.length; i++) {
const paragraph = paragraphs.items[i];
if (paragraph.text) {
const wordsRangeCollection = paragraph.getRange().split([" "]);
wordsRangeCollection.load("$none");
await wordsRangeCollection.context.sync();
console.log(wordsRangeCollection.items);
}
}
await context.sync();
const end = performance.now();
console.log(`Execution time: ${end - start} ms`);
});
}
not working
FAILURE
word-web-16.00.js:25 Uncaught (in promise) RichApi.Error
export async function run() {
return await Word.run(async (context) => {
const start = performance.now();
const paragraphs = context.document.body.paragraphs;
paragraphs.load("text");
await context.sync();
await Promise.all(
paragraphs.items.map(async (paragraph) => {
if (paragraph.text) {
const wordsRangeCollection = paragraph.getRange().split([" "]);
wordsRangeCollection.load("$none");
await wordsRangeCollection.context.sync();
console.log(wordsRangeCollection.items);
}
})
);
await context.sync();
const end = performance.now();
console.log(`Execution time: ${end - start} ms`);
});
}
Both your implementations have a context.sync
in a loop. (The map
method is a loop in disguise.) This is a performance killer. Please use the techniques in this article to get the context.sync
out of the loop: Avoid using the context.sync method in loops.