0

I've got the following code which does an ajax (initFunction.initFunction(email)) to validate a user email. The ajax works, however the response always returns 'undefined'

const somefunction = (email) => {
  let x = new Promise(function(resolve, reject) {
    let y = initFunction.initFunction(email) //ajax call which returns true
    resolve (y)
  });
  return x;
}
async function logFetch(email) {
  try {
    const response = await somefunction(email)
    .catch(function(ex) {console.log('error')});
    console.log(await response);
  }
  catch (err) {
    console.log('fetch failed', err);
  }
}
logFetch('foo@bar.com');

initFunction.initFunction():

  const xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
  xhr.open('GET', '/email/verify/'+email);
  xhr.onreadystatechange = function() {
    if (xhr.readyState>3 && xhr.status==200) {
      if (xhr.responseText == "unavailable") {
        return true
      } else if (xhr.responseText == "invalid") {
        return false
      } else if (xhr.responseText == "valid") {
        return true
      }
    }
  };
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin');
  xhr.send(null);

  return xhr;
jj1111
  • 607
  • 2
  • 10
  • 20
  • how does `initFunction` work? is it async? – Daniel A. White Mar 02 '17 at 21:37
  • You need to pass a callback / consume a promise from the actual async function. – SLaks Mar 02 '17 at 21:37
  • @SLaks where would I need to do this? Thanks for the response! – jj1111 Mar 02 '17 at 21:38
  • @DanielA.White it's an xhr which I haven't altered, so no probably not async – jj1111 Mar 02 '17 at 21:41
  • The **A** in AJAX stands for async. – SLaks Mar 02 '17 at 21:45
  • right I have grasped the acronym, and my ajax request worked before I tried to incorporate an async/await. Anyway biggest apologies for a newbie asking when stuck. – jj1111 Mar 02 '17 at 21:50
  • 1
    pls add the code of `initFunction.initFunction` – Balázs Édes Mar 02 '17 at 21:58
  • You need to put the `new Promise` inside the `initFunction` for it to return anything meaningful (without using callbacks) – Bergi Mar 02 '17 at 22:00
  • @BalázsÉdes - so my initFunction is async as well, so I'm not totally sure what the problem is still... any ideas? – jj1111 Mar 02 '17 at 22:51
  • @jj1111 Well you said `initFunction` would return `true`. It does not, it returns `xhr`. You are returning the boolean from the `onreadystatechange` callback, to nowhere. You will need to wrap the XHR in the promise, and then `resolve(true)` or `resolve(false)` (and `reject(…)` in case of a problem)! – Bergi Mar 02 '17 at 23:24

0 Answers0