[Solved] how to make an asynchronous javascript function synchronous


for others that will be in the same situation as I am, here is the solution.

first step, I made the captcha function to return a promise

function captcha() {
    return new Promise(function(resolve, reject) {
      grecaptcha.ready(function() {
        grecaptcha.execute(recaptcha_site_key, {action: 'run'}).then(function(token) {
          resolve(token);
        });
      });
    });
}

second step, async/await for the variable to become available

async function run() {
  let g_recaptcha_response = await captcha();
  document.forms['params'].elements['g_recaptcha_response'].value = g_recaptcha_response;
  let data = input();
  data = confirm(data);
  if (data['error'] === true) {
    return data;
  }
  let url = `${origin}/app/json`;
  data = request(url, data);
  // note: preparing for input / next request.
  document.forms['params'].elements['token_id'].value = data['token_id'];
  return data;
}

third step, create an IIFE at the top-level

(async function(){ let response = await run(); })();

3

solved how to make an asynchronous javascript function synchronous