【问题标题】:is it possible to wait until the execution of current method is executed是否可以等到当前方法的执行完成
【发布时间】:2020-02-26 10:48:54
【问题描述】:

我正在开发一个 Word 插件(Word API + Office.js),我正在使用内容控件,我正在尝试检查控件是否为空白,如果它为空白,我正在尝试设置一个标志“假”。

但由于异步性质,执行将移至下一行,而没有完全执行 CheckMandatoryFields 方法,因此强制标志始终为真。

有什么办法可以等到CheckMandatoryFields的执行完成

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

        });      

    }

【问题讨论】:

  • 设计 CheckMandatoryFields 以返回一个 Promise。然后将后面的代码放在then() 方法中。此外,在循环中使用Word.run 通常不是一个好习惯。尝试在 Word.run 内循环遍历数组。
  • @RickKirkham with word.run 是否有可能返回一个承诺?我对此感到困惑
  • @Common_Coder 你可以'Promisify'回调函数,看看here
  • @RickKirkham Word Api 是否支持承诺?

标签: office-js office-addins word-web-addins


【解决方案1】:

Officejs 方法的 Promisification 示例:

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

使用它:

getToken().then(res => {
   // Do stuff with token
}).catch(err => {
   // Handle error
})

【讨论】:

  • 将承诺在 word api 1.3 中工作?当我试图创建一个承诺时,我得到了未定义的错误
  • @Common_Coder 该错误意味着您的加载项在不支持 Promises 的 IE 中运行。 Office 有一个你可以使用的 Promises polyfill。只需将此代码添加到 JavaScript 文件的顶部:if (!window.Promise) { window.Promise = Office.Promise; } 示例,请参见 this file
猜你喜欢
  • 1970-01-01
  • 2020-12-07
  • 2019-09-01
  • 2013-08-09
  • 1970-01-01
  • 2022-06-28
  • 1970-01-01
  • 2020-12-20
  • 2018-04-05
相关资源
最近更新 更多