首页 > 解决方案 > 如何从 getAllInternetHeadersAsync 获取返回值?

问题描述

我创建了一个 Office 加载项,我想知道如何使用 getAllInternetHeadersAsync 获取 Internet 标头?我有以下代码,它将标头发送到控制台:

var headers = "";
// Get the internet headers related to the mail.
Office.context.mailbox.item.getAllInternetHeadersAsync(
     function(asyncResult) {
         if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
             headers = asyncResult.value;
             console.log(headers);

         } else {
            if (asyncResult.error.code == 9020) {
              // GenericResponseError returned when there is no context.
              // Treat as no context.
         } else {
              // Handle the error.
           }
       }
     }
  );
  console.log("headers = " + headers);

但是,标题似乎没有永久设置。第一个 console.log 显示标题的正确值。然而,最后一个 console.log 显示 headers 恢复为空。如何设置标头以便在 getAllInternetHeadersAsync 函数之后我仍然可以看到它?

谢谢!

标签: javascriptoffice365email-headers

解决方案


仔细查看您的控制台输出。您应该会发现代码末尾的输出console.log("headers = " + headers)显示在回调函数内部的输出之前。console.log(headers)

getAllInternetHeadersAsync()与许多 Office API 函数一样,顾名思义,它是一个异步函数。当您调用该函数时,它会在获取标头之前立即返回。因此,函数调用之后的任何代码都会立即执行。但是你还没有标题!

一段时间后,该函数获取标题并调用您的回调函数。现在您可以访问标题了。但是将这些标头存储在全局变量中并没有任何好处,因为您的其他代码不知道它们何时准备好。

您需要做的是:您需要查看标头的任何代码都应该在回调函数中,或者在您从回调代码调用的另一个函数中。这样,您的代码将具有可用的标头。

这就是您必须如何处理Async名称中的每个 Office API 函数。

正如@JaromandaX 在评论中指出的那样,您可以使用 aPromiseasync/ await,但您必须Promise自己创建,因为 Office API 不会为您执行此操作 - 它只是使用回调。同样使用async/await会限制您使用支持它的现代浏览器,或者如果您需要支持 Internet Explorer,则需要您使用编译器将您的代码转换为与 ES5 兼容的代码。

对于 Office API,最简单的方法是坚持使用xyzAsync函数提供的回调系统,并且只访问asyncResult.value回调内部或从回调内部调用的另一个函数。

如需更多阅读,请通过网络搜索异步 javascript找到许多更详细地解释这一点的文章。


推荐阅读