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?
source to share
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});
});
source to share