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

Outlook插件开发:调用getAsync返回Promise<pending>及undefined问题

问题分析与解决方案

核心问题是调用异步函数getTo()时未使用await,导致to变量拿到的是处于pending状态的Promise对象,而非实际的收件人数据。另外你的Promise封装存在错误:失败场景应该用reject而非resolve传递错误。

修复步骤

1. 修正Promise封装的错误处理

将失败分支的resolve(result.error)改为reject(result.error),确保错误能被正确捕获:

function createPromise() {
    return new Office.Promise(function (resolve, reject) {
        try {
            Office.context.mailbox.item.to.getAsync(
                function (result) {
                    console.log("in result fxn");
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        console.log("success");
                        console.log(result.value);
                        resolve(result.value);
                    } else {
                        console.log("failed");
                        console.error(result.error);
                        // 失败时用reject传递错误
                        reject(result.error);
                    }
                }
            );
        }
        catch (error) {
            console.log("failed promise");
            reject("failed to create promise");
        }
    });
}

2. 修改someFunction为异步函数并使用await

getTo()是异步函数,必须用await等待它完成才能拿到实际结果,因此需要将someFunction声明为async:

async function someFunction() {
    var nm = {};
    try {
        var to = await getTo();
        console.log("we are inside if to and to is: ");
        console.log(to);
        if (to && to.length > 0) {
            nm["eml"] = to[0].emailAddress;
            nm["first"] = to[0].givenName;
            nm["last"] = to[0].surname;
            nm["full"] = to[0].displayName;
        }
    } catch (err) {
        console.error("获取收件人失败:", err);
    }
    return nm;
}

3. 调用someFunction时处理异步逻辑

someFunction现在是async函数,调用它的地方必须通过await或.then()获取最终结果:

// 方式1:用await调用(需在async函数内)
async function callSomeFunction() {
    var recipientInfo = await someFunction();
    console.log(recipientInfo);
}

// 方式2:用.then()链式调用
someFunction().then(recipientInfo => {
    console.log(recipientInfo);
}).catch(err => {
    console.error(err);
});

补充说明

  • async函数默认返回Promise,因此调用方必须通过await或.then()获取最终值,无法直接同步赋值。
  • 添加try/catch可以有效捕获异步操作中的错误,避免程序异常崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 17:10:33