Outlook JavaScript开发:无法获取嵌套异步函数返回的MyMessage值
解决方案
根本原因
你调用的Office.context.mailbox.item.getAllInternetHeadersAsync是异步API,它接收的回调函数会在异步操作完成后才触发,而外层的confirmedsendheaders函数不会等回调执行,会直接跑完后续代码,所以不管是直接返回内部变量,还是在外层定义变量承接值,最后拿到的都是回调未执行时的初始值。
可直接使用的实现方案
方案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) } }) } // 调用方式:需要用到MyMessage的逻辑都放在回调内 confirmedsendheaders(function(MyMessage) { console.log(MyMessage) // 后续所有依赖MyMessage的代码都写在此处 })
方案2:包装为Promise使用async/await
如果习惯用await写法,可以把异步API包装为Promise,外层用async声明函数即可正常使用await:
// 封装为Promise function confirmedsendheaders() { 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) } }) }) } // 调用方式二选一 // 用法1:在async函数内使用await async function processMessage() { const MyMessage = await confirmedsendheaders() console.log(MyMessage) // 后续处理逻辑 } processMessage() // 用法2:用.then链式调用 confirmedsendheaders().then(MyMessage => { console.log(MyMessage) // 后续处理逻辑 })
之前尝试失败的原因说明
- 回调函数内部的return只会返回到异步API的内部逻辑,不会向外传递到
confirmedsendheaders的返回值 - 外层定义的承接变量在异步回调执行前就已经被return,拿到的永远是初始空值
- await仅可在
async标识的函数内使用,普通函数、普通回调内直接使用await会触发语法错误
内容的提问来源于stack exchange,提问作者user16953756
相关产品推荐
相关产品推荐

