1

I'm developing a Word Add-in (Word API + Office.js) where i am working with content controls, i am try to check whether control is blank, if it is blank i am trying to set a flag to "False".

but because of the async nature the execution is moving to next line with out fully executing CheckMandatoryFields method, hence mandatoryflag is always true.

is there any way to wait until the execution of CheckMandatoryFields is completed

 var mandatoryflag = "True";

 function Test()
    {

        CheckMandatoryFields();

        if (mandatoryflag)
        {
              document.getElementById('lblstatus').innerText += "Success" + " ";
        }
    }

    function CheckMandatoryFields() {

        var MadatoryFieldsList = ["Control1","Control2"];

        $.each(MadatoryFieldsList, function (index, element) {

            Word.run(function (context) {             
                var contentControls = context.document.contentControls.getByTag(element).getFirst();                
                contentControls.load('text');

                return context.sync().then(function () {
                    var text = contentControls.text;

                    if (text == "") {
                        document.getElementById('lblstatus').innerText += element + " is Mandatory" + " ";
                        mandatoryflag = "False";
                    }
                })
            });

        });      

    }
Common_Coder
  • 131
  • 6
  • 1
    Design `CheckMandatoryFields` to return a Promise. Then put the code that should come after it in a `then()` method. Also, its generally not a good practice to have a `Word.run` in a loop. Try to loop through the array, inside the `Word.run`. – Rick Kirkham Feb 26 '20 at 17:20
  • @RickKirkham with word.run is it possible to return a promise?? i am getting confused with this – Common_Coder Feb 27 '20 at 09:12
  • @Common_Coder You can 'Promisify' callback functions, take a look [here](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) – Lumpenstein Feb 27 '20 at 10:15
  • @RickKirkham whether promise is supported in Word Api ? – Common_Coder Feb 27 '20 at 13:03

1 Answers1

1

Example Promisification of an Officejs method:

private getToken = (): Promise<string> => {
    return new Promise((resolve, reject) => {
      Office.context.mailbox.getCallbackTokenAsync(
        {},
        (asyncResult): void => {
           if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
               resolve(asyncResult.value)
           } else {
               reject("GetCallbackToken failed")
           }
        })
    })
  }

Use it :

getToken().then(res => {
   // Do stuff with token
}).catch(err => {
   // Handle error
})
Lumpenstein
  • 1,250
  • 1
  • 10
  • 27
  • will promise work in word api 1.3 ?? when i tried to create a promise i am getting undefined error – Common_Coder Feb 27 '20 at 12:37
  • 1
    @Common_Coder That error means your add-in is running in IE which does not natively support Promises. Office has a Promises polyfill that you can use. Just add this code to the top of the JavaScript file: `if (!window.Promise) { window.Promise = Office.Promise; }` For an example, see [this file](https://github.com/OfficeDev/Office-Add-in-NodeJS-SSO/blob/bd58f49435a318362888fb1f78fc43e7d6ce1650/Complete/public/javascripts/fallbackAuthDialog.js). – Rick Kirkham Feb 28 '20 at 21:07