Search code examples
javascriptreactjsasynchronousasync-await

How to use JavaScript await on user input in an async function


I ran into a situation which requires me to popup a window for user to make a choice, after it's closed, based on the user input and make another http request. I don't know how to do a await after the popup.

async function checkRemote(url1, url2)  {

    var resp
    resp = await fetch(url1).then(r => r.json())

    if (r.condition1 == 100) {
        setState({showPopup: true}) //in a reactjs app
        //how do I do await here to wait for the popup being closed
        //get the user choice in variable "proceed"
    }
    if (proceed) {
        resp = await fetch(url2)
        //do some more work
    }
}

Solution

  • Create a promise, resolve it inside popup closed event handler, and await for it inside your function.

    var popupClosed = new Promise(function(resolve, reject) {
       // create popup close handler, and call  resolve in it
    });
    
    async function checkRemote(url1, url2)  {
    
        var resp
        resp = await fetch(url1).then(r => r.json())
    
        if (r.condition1 == 100) {
            setState({showPopup: true}) //in a reactjs app
            var closed = await popupClosed;
        }
        if (proceed) {
            resp = await fetch(url2)
            //do some more work
        }
    }