Office.js中无法将函数值存入变量问题求助
Outlook加载项自定义属性读取问题解决方案
问题原因
loadCustomPropertiesAsync是异步方法:它不会同步返回自定义属性值,而是在操作完成后触发传入的回调函数。直接将该方法的返回值赋值给test,得到的是异步操作的状态对象,而非目标属性值,因此test显示为undefined。- 异步执行顺序:JavaScript中异步操作不会阻塞后续代码执行,
console.log会在loadCustomPropertiesAsync的回调函数运行前就执行,此时还未获取到自定义属性,所以打印结果为undefined。
解决方法
方法1:在回调函数内处理逻辑
将需要使用自定义属性的代码放在回调函数内部,确保在属性加载完成后再执行:
const mailbox = Office.context.mailbox.item; mailbox.loadCustomPropertiesAsync(function (result) { // 先判断异步操作是否成功 if (result.status === Office.AsyncResultStatus.Succeeded) { const customProps = result.value; const test = customProps.get("CustomMeeting"); console.log('Custom property', test); // 在这里编写需要使用test变量的后续业务逻辑 } else { // 处理加载失败的情况 console.error('加载自定义属性失败:', result.error); } });
方法2:用Promise封装后使用async/await(更优雅的现代写法)
先将异步方法封装为Promise,再通过async/await实现同步风格的异步代码:
// 封装异步方法为Promise function loadCustomProperties() { return new Promise((resolve, reject) => { Office.context.mailbox.item.loadCustomPropertiesAsync(result => { if (result.status === Office.AsyncResultStatus.Succeeded) { resolve(result.value); } else { reject(result.error); } }); }); } // 使用async/await调用 async function getCustomProperty() { try { const customProps = await loadCustomProperties(); const test = customProps.get("CustomMeeting"); console.log('Custom property', test); // 后续业务逻辑写在这里 } catch (error) { console.error('加载自定义属性失败:', error); } } // 执行函数 getCustomProperty();
内容的提问来源于stack exchange,提问作者Shiv Yadav
相关产品推荐
相关产品推荐

