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
}
}
Async/await helps you write synchronous-looking JavaScript code that works asynchronously. Await is in an async function to ensure that all promises that are returned in the function are synchronized.
The async-await syntax helps with readability, allowing you to write the code as if it were using synchronous call patterns. To enable this method of communication, you'll need to modify your function prototype. In the declaration of the function prototype, before the word function, add the keyword async.
The await keyword is used in an async function to ensure that all promises returned in the async function are synchronized, ie. they wait for each other. Await eliminates the use of callbacks in .
Asynchronous requests will wait for a timer to finish or a request to respond while the rest of the code continues to execute.
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
}
}
Based on @hikmat-gurbanli's answer, here is a working solution. The idea is to save the resolve function so some handle can call it in the future to unblock the async function.
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)
}
A handler can just call savedResolve.resolve("Yes")
and it will unblock the async function checkRemote
at line var result = await popupClosed;
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