javascript - 如何从 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 函数之后我仍然可以看到它?
谢谢!
解决方案
仔细查看您的控制台输出。您应该会发现代码末尾的输出console.log("headers = " + headers)
显示在回调函数内部的输出之前。console.log(headers)
getAllInternetHeadersAsync()
与许多 Office API 函数一样,顾名思义,它是一个异步函数。当您调用该函数时,它会在获取标头之前立即返回。因此,函数调用之后的任何代码都会立即执行。但是你还没有标题!
一段时间后,该函数获取标题并调用您的回调函数。现在您可以访问标题了。但是将这些标头存储在全局变量中并没有任何好处,因为您的其他代码不知道它们何时准备好。
您需要做的是:您需要查看标头的任何代码都应该在回调函数中,或者在您从回调代码调用的另一个函数中。这样,您的代码将具有可用的标头。
这就是您必须如何处理Async
名称中的每个 Office API 函数。
正如@JaromandaX 在评论中指出的那样,您可以使用 aPromise
和async
/ await
,但您必须Promise
自己创建,因为 Office API 不会为您执行此操作 - 它只是使用回调。同样使用async
/await
会限制您使用支持它的现代浏览器,或者如果您需要支持 Internet Explorer,则需要您使用编译器将您的代码转换为与 ES5 兼容的代码。
对于 Office API,最简单的方法是坚持使用xyzAsync
函数提供的回调系统,并且只访问asyncResult.value
回调内部或从回调内部调用的另一个函数。
如需更多阅读,请通过网络搜索异步 javascript找到许多更详细地解释这一点的文章。
推荐阅读
- javascript - NPM 安装:grpc@1.24.2 和 node@6.16.0 无法安装预构建的二进制文件
- css - 对身体的看法,有什么办法可以打破堆叠上下文?
- c# - 如何在 C# 中模拟数据库连接?
- java - 为什么每个循环 Selenium 都使用相同的 WebElement?
- angular - 如何在订阅处于活动状态时更改从 observable 返回的数据?
- image - Laravel 在 Blade 文件中包含图像而不是来自公共文件夹
- javascript - “未捕获的 TypeError:$(...).autocomplete 不是函数”和 Oracle Apex
- javascript - 如何避免在使用打字稿生成的表单中换行?
- x86 - 英特尔的 CLWB 指令使缓存行无效
- visual-studio-code - 使用 VScode 访问远程机器浏览器