0

I'm trying to simulate the confirm function of javascript. But it doesn't work. Where am I making a mistake?

function func(){
    $('body').on('click', '.true', function() {
        return true;
    });

    $('body').on('click', '.false', function() {
        return false;
    });
}


function test(){
    var r = func();

    if(r==false){
        alert('false');
        return false;
    }

    alert('it works');
}

jsfiddle

pmxd
  • 3
  • 1
  • What happens if you click the button twice? Will it return twice? Also, you can't represent an *asynchronous action* with a *synchronous `function`*. – Jonas Wilms Oct 24 '19 at 16:07
  • Possible duplicate of [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) – Carcigenicate Oct 24 '19 at 16:10

1 Answers1

1

confirm halts the codes execution of the browser, until a button gets clicked. That's why confirm can return synchronously and behave like a regular function. You cannot halt the browsers execution from within JS, so this is entierely impossible (or if you do, the user cannot input anything).

You could however create and return a promise (which can then be resolved asynchronously):

 function func(){
  return new Promise((resolve, reject) => {
    $('body').once('click', '.true', function() { // Only listen to *one* click instead of keeping this listener forever
        resolve(true); // resolve the promise if clicked
    });

   $('body').once('click', '.false', function() {
     resolve(false);
   });
  });
}

That can then be used as:

 async function test(){ // has to be async, so that the execution can be haltet
   var r = await func(); // halts till click

   if(!r) { // reads "if not r"
    alert('false');
  } else alert('it works');
}

test();

Read On

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151