Suspending async javascript function until user action

I have an async function and I want it to execute at a specific point, pause execution, and resume execution of the rest of the function when the user does a specific action (like clicking a button). I've 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 the way I would like. Async does not wait for user action. As I understand it, this is because the promise is instantly rejected because the "changed" flag is "false". How can I fix this code to work as expected? Is it even possible?

+3


source to share


2 answers


Don't use this flag changed

at all. You cannot watch a variable or wait until it has a specific value (other than polling, but you don't want that). Instead, you should simply call the callback resolve

from your click handler:



var clickPromise = new Promise(function(resolve) {
    document.getElementById('change').addEventListener('click', function(e) {
        resolve(e);
    }, {once: true});
});

      

+6


source


You just need a way to resolve your promise from the outside, but what about:

let outsideResolve;
let promise = new Promise(function(resolve) {
    outsideResolve = resolve;

});

      



You can now call externalResolve from your click handler.

+4


source







All Articles