Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pausing javascript async function until user action

I have async function and I want it to execute to certain point, pause execution, and resume execution rest of function when user makes certain action (clicks a button for example). I tried this:

let changed = false;

let promise = new Promise(function(resolve, reject){

    if(changed){

        resolve('success');
    }else{

        reject('failure');
    }
});

async function test(){

    console.log('function started');
    console.log('before await');

    try{

        const fulfilledValue = await promise;
        console.log(fulfilledValue);
    }catch(failure){

        console.log(failure);
    }

    console.log('after await');
};

document.getElementById('change').addEventListener('click', function(){

    if(!changed){

        console.log('changed = true');
        changed = true;
    }else{

        changed = false;
    }
});

test();

However it doesn't work as I would like to. Async function doesn't wait till user action. As I understand it happens because promise is instantly rejected, because "changed" flag is initialy set to false. How can I fix this code to work as expected? Is it possible at all?

like image 771
Furman Avatar asked Dec 14 '22 21:12

Furman


1 Answers

Don't use that changed flag at all. You cannot watch a variable or wait until it has a certain value (except for polling, but you don't want that). Instead, you should simply call the resolve callback from the click handler:

var clickPromise = new Promise(function(resolve) {
    document.getElementById('change').addEventListener('click', function(e) {
        resolve(e);
    }, {once: true});
});
like image 196
Bergi Avatar answered Dec 21 '22 10:12

Bergi