You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Outlook JS调用getAllInternetHeadersAsync无法返回嵌套函数值问题

核心问题原因

Office.context.mailbox.item.getAllInternetHeadersAsync 是异步API,调用后不会阻塞后续代码执行,外层函数会先跑完return逻辑,等异步请求拿到邮件头结果后才会执行回调内的代码,所以你之前的尝试都拿不到MyMessage的返回值:

  • 回调内的return只会把值返回给异步方法内部,不会传递到外层confirmedsendheaders函数
  • 外层定义变量接收的方案里,return语句执行时异步回调还没执行,变量还没被赋值,永远是空值
  • await只能在标记了async的函数内使用,普通回调内直接写await会触发语法错误

可用解决方法

方法1:回调传参

把后续需要用到MyMessage的逻辑封装成回调函数,传入异步方法,等拿到结果后触发回调执行:

function confirmedsendheaders(callback) {
  Office.context.mailbox.item.getAllInternetHeadersAsync(function (asyncResult) {
     if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
        const 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
        // 触发回调传递结果
        callback(MyMessage)
    }
  })
}

// 调用示例:打印结果
confirmedsendheaders(function(MyMessage) {
  console.log(MyMessage)
  // 所有需要用到MyMessage的逻辑都写在这里
})

方法2:封装Promise搭配async/await

把异步逻辑封装成Promise,用async/await语法写更清晰的同步风格代码:

function confirmedsendheaders() {
  // 封装为Promise返回
  return new Promise((resolve, reject) => {
    Office.context.mailbox.item.getAllInternetHeadersAsync(function (asyncResult) {
      if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
        const 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
        resolve(MyMessage)
      } else {
        reject(asyncResult.error)
      }
    })
  })
}

// 调用示例
async function getMyMessage() {
  try {
    const MyMessage = await confirmedsendheaders()
    console.log(MyMessage)
    // 所有需要用到MyMessage的逻辑都写在这里
  } catch (err) {
    console.error("获取失败:", err)
  }
}

getMyMessage()

内容的提问来源于stack exchange,提问作者so user

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 16:24:04