javascriptpromiseoffice-jsoutlook-addinoffice-addins

Why can't I get a result from the Office.context.mailbox.item.to.getAsync function?


Writing an Outlook Add-In and trying to get the recipients from message compose mode using the Office Javascript API. I can see successful results in the console logs but I only get undefined as a result.

I created a promise:

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);    //console shows accurate results
                        resolve(result.value);
                    } else {
                        console.log("failed");
                        console.error(result.error);
                        resolve(result.error);
                    }
                }
            );
        }
        catch (error) {
            console.log("failed promise");
            reject("failed to create promise");
        }
    });
}

And then called the promise using await:

async function getTo() {
    return await createPromise();
}

But the function that calls getTo is logging that the promise is pending.

function someFunction() {
    var to = getTo();
    var nm = {};
    if (to) {
        console.log("we are inside if to and to is: ");
        console.log(to);              //this logs Promise {<pending>}
        if (to.length > 0) {
            nm["eml"] = to[0].emailAddress;
            nm["first"] = to[0].givenName;
            nm["last"] = to[0].surname;
            nm["full"] = to[0].displayName;
        }
    }
    return nm;
}

I've tried several approaches and read many Microsoft docs (hoping what I'm reading isn't out of date) and still no luck. TIA.


Solution

  • Got it working. I just needed to make someFunction asynchronous and await the result from getTo. Adding async/await all the way up the chain of functions allowed the results of the promise to be used as intended.

    So someFunction became:

    async function someFunction() {
        var to = await getTo();
        var nm = {};
        if (to) {
            console.log("we are inside if to and to is: ");
            console.log(to);              //this logs Promise {<pending>}
            if (to.length > 0) {
                nm["eml"] = to[0].emailAddress;
                nm["first"] = to[0].givenName;
                nm["last"] = to[0].surname;
                nm["full"] = to[0].displayName;
            }
        }
        return nm;
    }
    

    Added async/await to the function that consumed someFunction, and so on.