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?
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});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With