0

I am trying to set up a promise that would only return the outcome after the ajax call

However in my code the outcome returns null before the ajax is completed, from console log i can also see that it is returned before completion of the checkuser function.

How can i achieve this , do I have to make a timeout loop waiting for the outcome to change value to 0 or 1 and set a timeout limit?

 function checkUser() {  
  return new Promise((resolve, reject) => {  
  $.ajax({
  type: "POST",
  url: 'checkUserAvail.php',
  data: {value: value},
  success:  function (data) {
        resolve(data);
      },
  error: function (error)  
        {
         reject(error);
        }
   })
  })
}
    
checkUser()
  .then((data) => {
                console.log(data);
                if (data == 1)
                        {
                         outcome= 1;
                        }
                if (data == 0)
                            {   
                            outcome= 0;
                            }
                    
                })
  .catch((error) => {
    alert("An error ocurred");
  })

console.log(outcome);
return outcome;

Ryan
  • 159
  • 11
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Peter B Jul 14 '20 at 11:23
  • You cannot return a value that relies on an async call, unless you also make the function async, `await` the Promise, then return its result. You can never get back to synchronous code again, since any involved sync function can only return a Promise, never an actual result. Here's a code example I wrote for another question: https://jsfiddle.net/khrismuc/ewbtc2Lr/ –  Jul 14 '20 at 12:31
  • thanks @ChrisG . Ill change my code – Ryan Jul 14 '20 at 12:41
  • @ChrisG It seems that the async function is not supported by internet explorer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function – Ryan Jul 14 '20 at 13:08
  • True; in that case you need to stick to Promises. Instead of *returning* `outcome`, have your `then()` callback run the code that requires the value of `outcome`. –  Jul 14 '20 at 13:10
  • Example code: https://jsfiddle.net/0cxt1e8r/ –  Jul 14 '20 at 13:20

1 Answers1

0

console.log(outcome);
return outcome;

This bit of code should be in the then block.

Whats happening is that you're trying to return outcome before the Promise resolves.

Angel
  • 100
  • 8
  • This part of the script is in a validator function. Even if I put the return outcome in the then block. The function returns with no result before the then block completes – Ryan Jul 14 '20 at 11:33