首页 > 解决方案 > 无法返回嵌套调用的 Outlook 函数

问题描述

我有一个 Outlook javascript 函数,我试图MyMessage在完整函数之外获取 console.log 的值,但是我遇到了麻烦。

function confirmedsendheaders() {
  Office.context.mailbox.item.getAllInternetHeadersAsync(function (asyncResult) {
     if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
     MyMessage = `Hello Support, <br>
<br>
This is an automated email from` + Office.context.mailbox.userProfile.displayName + ` to check if this is spam. <br>
<br>      
<b>Email Header Information: </b>
<br>
`+ asyncResult.value
      return MyMessage

    }

  })
}

我还尝试将返回值放在有问题的变量旁边,但没有运气:

function confirmedsendheaders() {
  Office.context.mailbox.item.getAllInternetHeadersAsync(function (asyncResult) {
     if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
     return MyMessage = `Hello Support, <br>
<br>
This is an automated email from` + Office.context.mailbox.userProfile.displayName + ` to check if this is spam. <br>
<br>
<b>Email Header Information: </b>
<br>
`+ asyncResult.value
      

    }

  })
}

我读到这个:Return value from nested function in Javascript,它提到需要调用第二个函数,但它看起来像是在开始时被调用,除非我错了。有任何想法吗?

编辑:我还尝试让一个变量与嵌套函数的结果相同,以查看它是否有效但没有运气。我从这篇文章中看到了这个想法:https ://stackoverflow.com/a/3373953

第三次尝试:

function confirmedsendheaders() {
var secret = ''
  Office.context.mailbox.item.getAllInternetHeadersAsync(function (asyncResult) {
     if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
     MyMessage = `Hello Support, <br>
<br>
This is an automated email from` + Office.context.mailbox.userProfile.displayName + ` to check if this is spam. <br>
<br>
<b>Email Header Information: </b>
<br>
`+ asyncResult.value
      secret = MyMessage.secret

    }

  })
return secret
}

这不是异步函数。我试图添加等待,它说:Uncaught SyntaxError: **await is only valid in async** functions and the top level bodies of modules 第四次尝试

function confirmedsendheaders() {
var secret = ''
  Office.context.mailbox.item.getAllInternetHeadersAsync(function (asyncResult) {
     var secret = await if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
     MyMessage = `Hello Support, <br>
<br>
This is an automated email from` + Office.context.mailbox.userProfile.displayName + ` to check if this is spam. <br>
<br>
<b>Email Header Information: </b>
<br>
`+ asyncResult.value
    }

  })
return secret
}

标签: javascript

解决方案


想通了那个问题。事实证明这Office.context.mailbox.item.getAllInternetHeadersAsync是异步的,但它看起来与普通的异步函数不同。我尝试了多种方法来尝试等待该值,但 console.log 一直说 await 只能与异步函数一起使用,这让我相信Office.context.mailbox.item.getAllInternetHeadersAsync即使它的名称也不是异步的。

在阅读了这篇解释更多关于 Office 应用程序功能的帖子后,我能够猜到足够多的时间来正确理解:https ://stackoverflow.com/a/63491150

Office.context.mailbox.item.getAllInternetHeadersAsync(async function (asyncResult){})

推荐阅读