Pausing javascript async function until user action

Viewed 1489

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?

2 Answers
Related