Search code examples
office-jsword-addins

Further looking into "Avoid context.sync in loops"


Article Avoid using the context.sync method in loops renders incredible help on the Word add-in I am developing. I see huge performance improvement after adopting the technique introduced in this article.

This really made my day. Now there is only one sync-loop left that I am not sure how to deal with it. Here is the sample code. The culprit function with context.sync() runs inside a loop, forming the sync-loop that drives me nuts. Any idea how to optimize it? For some reason, the two functions cannot be merged.

async function testFunc (ranges: Word.RangeCollection) {
  for (let i=0; i<1000; i++) {
    await culprit(ranges.items[i]);
  }
}
async function culprit (range: Word.Range) {
  range.load("text");
  await range.context.sync();
}

Solution

  • Try loading in a loop, context sync then read the actual text in a second loop.

    (Note: Not tested, but seems to have positive feedback in the comments.)

    Basically:

    async function testFunc (ranges: Word.RangeCollection) {
      for (let i=0; i<1000; i++) {
        ranges.items[i].load('text');
      }
      await context.sync()
      for (let i=0; i<1000; i++) {
        // read the text here
      }
    }