1
votes

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";
                    }
                })
            });

        });      

    }
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
@RickKirkham with word.run is it possible to return a promise?? i am getting confused with this - Common_Coder
@Common_Coder You can 'Promisify' callback functions, take a look here - Lumpenstein
@RickKirkham whether promise is supported in Word Api ? - Common_Coder

1 Answers

1
votes

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
})