hretic
hretic

Reputation: 1095

Async/await doesn't work as intended

I wrote this code based on my understanding of Async/await and how it works. Basically i want my run() function to wait for captcha value to be set by clicking button and set_captcha function and then run the rest of the code

var captcha = false ;

function get_captcha() {
  return new Promise(function(resolve , reject ) {
    if(captcha === false ){
      reject(captcha );
    } else {
      resolve(captcha);
    }
  });
}

async function run() {
  var captcha = await get_captcha();
  console.log( ' captcha confirm -> ' + captcha );
}

run().then(function(){ console.log('done')});

function set_captcha(){
  captcha = 123;
}

</script>
<button type="button" onclick="set_captcha();">captcha</button>

but obviously Im missing something. When I run the code I get this error in console:

Uncaught (in promise) false

and when I click the button and call set_captcha() nothing happens.

Upvotes: 2

Views: 1779

Answers (1)

libik
libik

Reputation: 23049

You can think about async/await more like syntactic sugar that uses promises.

If the function is async it means it always return promise. That is the reason why you can await only in async method - as it always remains in a promise chain, it can return you the value inside async function - However when you return something out of that function, its always promise again.

Same as promises - once you are inside promise chain, you cant get value "outside of promiseChain" (like you can save it to some global variable, but you cannot return value directly from the chain - you can return only promise that can be resolved with a value).

You can rewrite any async function to promise chains and vice versa

This function:

async function run() {
    var captcha = await get_captcha();
    console.log( ' captcha confirm -> ' + captcha );
}

is equal to this one:

function run() {
    return get_captcha().then(captcha => {
       console.log( ' captcha confirm -> ' + captcha );
    });
}

The error: At beginning, captcha is false, therefore you reject promise at if(captcha === false ) reject(captcha ); with value false and you do not catch it, which ends with Uncaught (in promise) false

Upvotes: 1

Related Questions