0

I am trying to create an add-in for the outlook windows application. The following code should copy the email body to the clipboard, but it doesn't do that. I need to press the run button two times in order to get the content copied, but I need to copy the content from the first time! What is wrong with my code?

var messageBody = "";
export async function run() {
    Office.context.mailbox.item.body.getAsync(
        Office.CoercionType.Text,
        function (asyncResult) {
            if (asyncResult.status !== Office.AsyncResultStatus.Succeeded) {
                messageBody = asyncResult.error;
            } else {
                messageBody = asyncResult.value;
            }
        });

    copyToClipboard(messageBody)
}

function copyToClipboard(text) {
    var copyhelper = document.createElement("input");
    copyhelper.className = 'copyhelper'
    document.body.appendChild(copyhelper);
    copyhelper.value = text;
    copyhelper.select();
    document.execCommand("copy");
    document.body.removeChild(copyhelper);
}
Bod
  • 1
  • 2
  • 2
    you would put `copyToClipboard(messageBody)` INSIDE `function(asyncResults) {...}` – TKoL Oct 13 '20 at 16:57
  • 1
    I would suggest reading this: [How to return an asynchronous value](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) as the issue of asynchronous timing is covered there. Basically, your function `run()` returns BEFORE the asynchronous value has been retrieved so you are trying to use `messageBody` before it has a value in it. You will need to communicate back the asynchronous result with either a callback or a promise or an event or you can use the async value inside the callback where it is retrieved. – jfriend00 Oct 13 '20 at 17:01

0 Answers0