Search code examples
javascriptoffice-jsoutlook-web-addins

Wrap body.getAsync() inside a sync function


So I was following a tutorial to build an Outlook Add-in. However, the demo does not display the body of the message.

I also learned from the doc that I can call the getAsync to access to the body but it does not work. Do I need to use async await here?

Here is the code:

function loadProps() {
  $("#attachments").html(buildAttachmentsString(item.attachments));
  $("#cc").html(buildEmailAddressesString(item.cc));
  $("#conversationId").text(item.conversationId);
  $("#from").html(buildEmailAddressString(item.from));
  $("#internetMessageId").text(item.internetMessageId);
  $("#normalizedSubject").text(item.normalizedSubject);
  $("#sender").html(buildEmailAddressString(item.sender));
  $("#subject").text(item.subject);
  $("#to").html(buildEmailAddressesString(item.to));
  $("#body").text(buildEmailBodyString()); //async function
}

function buildEmailBodyString() {
  Office.context.mailbox.item.body.getAsync(Office.CoercionType.Text, function callback(resText) {
    return resText.value;
  });
}

Solution

  • Your issue is that your buildEmailBodyString fires off getAsync and exists immediately. It isn't returning restText.value from the function because the function already existed.

    function buildEmailBodyString() {
      // 1. Fires function
      Office.context.mailbox.item.body.getAsync(Office.CoercionType.Text, function callback(resText) {
        // 3. returns a value to nothing
        return resText.value;
      });
      // 2. Exits function
    }
    

    One solution here would be to set $("#body") from within the callback:

    function buildEmailBodyString() {
      Office.context.mailbox.item.body.getAsync(Office.CoercionType.Text, function callback(resText) {
        $("#body").text(resText.value);
      });
    }
    

    You could also drop buildEmailBodyString entirely and call it within loadProps directory. This would simplify the code so it's a bit easier grok down the road:

    function loadProps() {
      $("#attachments").html(buildAttachmentsString(item.attachments));
      $("#cc").html(buildEmailAddressesString(item.cc));
      $("#conversationId").text(item.conversationId);
      $("#from").html(buildEmailAddressString(item.from));
      $("#internetMessageId").text(item.internetMessageId);
      $("#normalizedSubject").text(item.normalizedSubject);
      $("#sender").html(buildEmailAddressString(item.sender));
      $("#subject").text(item.subject);
      $("#to").html(buildEmailAddressesString(item.to));
    
      // Retrieve Email Body
      Office.context.mailbox.item.body.getAsync(Office.CoercionType.Text, function callback(resText) {
        $("#body").text(resText.value);
      });
    }