简体   繁体   English

暂停javascript异步功能直到用户操作

[英]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. 据我所知,这是因为承诺立即被拒绝,因为“changed”标志最初设置为false。 How can I fix this code to work as expected? 如何修复此代码以按预期工作? Is it possible at all? 有可能吗?

Don't use that changed flag at all. 根本不要使用那个changed旗帜。 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: 相反,您应该只需从click处理程序调用resolve回调:

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

You just need a way to resolve your Promise from outside, what about: 你只需要一种从外面解决你的承诺的方法,那么:

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

});

You can now call outsideResolve from your click handler. 您现在可以从单击处理程序中调用outsideResolve。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM