Get value from an async function in Outlook Web Addin [closed]

Posted on

Problem

I’m working on an Outlook Web Addin that gets the email body. So in the Office API you could get the email body in two types: Simple Text and Html.

Our requirement is to get the HTML format so this is easy, however, even if the email body is empty the HTML format still returns a value which is the HTML elements but does not have contents in it. So my solution is to check first for the Simple Text version of the email body then if there is a content get the HTLM format version.

Please see the below codes:

var mailItem = Office.context.mailbox.item;

mailItem.body.getAsync(Office.CoercionType.Text, function (result) {
    if (result.status === Office.AsyncResultStatus.Succeeded) {
        var normalizeValue = null;

        if (result.value) {
            normalizeValue = result.value.trim();
        }

        if (normalizeValue !== '') {
            mailItem.body.getAsync(Office.CoercionType.Html, function (result) {
                if (result.status === Office.AsyncResultStatus.Succeeded) {
                    // the value will be initialized in input value
                    $('#body').val(result.value.trim());
                }
            });
        }
    }
});

I would like to get the value from the ‘Text’ type and pass this in a variable then check the variable then run the getAsync for the html version separately instead of having the codes inside the method of body.getAsync. Or anything the code could improve?

Solution

I would suggest you could use Promise.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

If you don’t want additional library for Promise, you could use Deferred from jQuery also. https://api.jquery.com/deferred.promise/

Leave a Reply

Your email address will not be published. Required fields are marked *