如何在异步函数中对用户输入执行javascript等待

pkt*_*der 6 javascript asynchronous async-await

我遇到了一种情况,需要我根据用户输入弹出一个窗口让用户做出选择,然后根据用户输入进行另一个 http 请求。我不知道如何在弹出窗口后等待。

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
    }
}
Run Code Online (Sandbox Code Playgroud)

Hik*_* G. 7

创建一个承诺,在弹出关闭事件处理程序中解决它,并在函数中等待它。

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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你能提供一个虚拟处理程序来调用其中的解析吗? (2认同)