'How to wait for async function response in outlook addin

I am working on developing outlook addin using Javascript (newbie to JS). After collecting all sendmail details, we have post the details to server and wait for the result. Based on the result, the sendmail should be allowed / blocked.

getAllMailDetails() is the callback for ItemSend event in addin manifest file and outlook is calling my addin function when a new mail is sent.

But allowBlockMail() is immediately called without waiting for the async. Since Javascript is single threaded (https://www.freecodecamp.org/news/async-await-javascript-tutorial/), how do I wait for the response to be included ?

let serverresp = "empty client";

function getAllMailDetails(event) {

  runfetch(event);
  allowBlockMail(event);
}

function allowBlockMail(event) {
  item = Office.context.mailbox.item;
  item.subject.getAsync(
    { asyncContext: event },
    function (asyncResult) {
      item.notificationMessages.addAsync('NoSend', { type: 'errorMessage', message: serverresp });
        asyncResult.asyncContext.completed({ allowEvent: false });
        return;
    }
  )
}

async function runfetch(event) {
  let user = {
    name: 'Addin Fetch 1234',
    surname: 'Smith'
  };

  
  serverresp = "before POST";

  try{
  let response = await fetch('https://localhost:4431/something.aspx', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    },
    body: JSON.stringify(user)
});

  if (response.ok) { // if HTTP-status is 200-299
    // get the response body (the method explained below)
    serverresp = await response.text();
  } else {
    serverresp = "http-error";
  }
}
catch(err) {
  serverresp = "caught exception";
}
}


Solution 1:[1]

One of the simplest ways is in the getAllMailDetails function you just need to call the single function:

function getAllMailDetails(event) {

  runfetch(event);
}

And when the fetch is done you may call the other one:

if (response.ok) { // if HTTP-status is 200-299
    // get the response body (the method explained below)
    serverresp = await response.text();
    // your processing results
    allowBlockMail(event);
  } else {
    serverresp = "http-error";
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eugene Astafiev