我遇到了一种情况,需要我弹出一个窗口,让用户在关闭后根据用户输入做出选择,并发出另一个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
    }
}发布于 2018-06-25 05:34:01
创建promise,在popup closed事件处理程序中解析它,并在函数中等待它。
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
    }
}发布于 2018-06-26 22:11:21
基于@hikmat-gurbanli的回答,这里有一个可行的解决方案。其思想是保存resolve函数,以便将来某个句柄可以调用它来解除异步函数的阻塞。
const fetch = require('node-fetch')
var savedResolve;
test("http://localhost/prod/te.php");
async function test(url) {
    await checkRemote(url)
    console.log("completed")
}
var popupClosed = new Promise(function(resolve, reject) {
   // create popup close handler, and call  resolve in it
   console.log("got here")
   savedResolve = resolve;
});
async function checkRemote(url1)  {
    var resp
    resp = await fetch(url1).then(r => r.text())
    console.log("resp " + resp)
    //setState({showPopup: true}) //in a reactjs app
    var result = await popupClosed;
    console.log("result: ")
    console.log(result)
}处理程序可以只调用savedResolve.resolve("Yes"),它将在var result = await popupClosed;行取消阻塞异步函数checkRemote
https://stackoverflow.com/questions/51013412
复制相似问题