Replace text in MS Word with a Basic API Call (JavaScript)

383 views Asked by At

I referenced the following Stack Overflow article for this code. I am trying to create a word template with certain text placeholders (like #APIdata#) that get replaced with data from an API call when the JavaScript is run. I'm using Script Lab to run the JavaScript.

Here's my code:

// Load API data
fetch("https://fc.prestoapi.com/api/comp?component_id=11")
  .then(function (response) {
    return response.json();
  })
  .then(function (result) {
  // Return the first item in the array and the value for the value_decimal key  
  let output = result[0].value_decimal;
  // Make APIoutput available throughout the script as a variable
  const APIoutput = output;
  })
  .catch(function (err) {
    console.log('error: ' + err);
  });

Word.run(function (context) {
  // Queue a command to search the document with a wildcard
  // for any string of characters that starts with 'to' and ends with 'n'.
  var searchResults = context.document.body.search("#APIdata#", { matchWildcards: true });

  // Queue a command to load the search results and get the font property values.
  context.load(searchResults, "text");

  // Synchronize the document state by executing the queued commands,
  // and return a promise to indicate task completion.
  return context.sync().then(function () {
    console.log("Found count: " + searchResults.items.length);
    // Queue a set of commands to change the font for each found item.
    for (var i = 0; i < searchResults.items.length; i++) {
      console.log(searchResults.items[i].text);
      searchResults.items[i].insertText(APIoutput, "Replace");
      return context.sync();
    }
    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync();
  });
}).catch(function (error) {
  console.log("Error: " + JSON.stringify(error));
  if (error instanceof OfficeExtension.Error) {
    console.log("Debug info: " + JSON.stringify(error.debugInfo));
  }
});

The code works when I replace the APIoutput variable in line 31 with some other text, so I assume it's an issue with the variable, but it's not giving me an error message and I've tried all I know how to do to debug it, so any help to get it working would be much appreciated.

1

There are 1 answers

0
MSFT-Jipyua On

I think you should put Word.run() related API call inside the following promise to make sure the APIoutput variable is really initialized.

.then(function (result) {
  // Return the first item in the array and the value for the value_decimal key  
  let output = result[0].value_decimal;
  // Make APIoutput available throughout the script as a variable
  const APIoutput = output;