I need to modify some legacy javascript code. There's a place where I want to wait until the user presses one of two buttons and then continue with the program flow (like prompt()
function). How can this be achieved ?
But in some case, Javascript behaves as asynchronous, such as in AJAX or Axios calls. It makes a call to the API but does not wait for the API to return result, and progresses with the next queued event.
Use async/await to Wait for a Function to Finish Before Continuing Execution. Another way to wait for a function to execute before continuing the execution in the asynchronous environment in JavaScript is to use async/wait .
Simply create a promise and store the resolve function outside its scope in a global variable. Then let the program wait for the promise to resolve (using "async" and "await"). The promise is resolved on a button click by calling that global variable. I used this technique in a chess program to wait for the answer to a promotion popup window:
var _promote; /* resolve-function reference */
async function promote_piece(pce, fld, clr) {
var type;
(...)
show_mpw(clr); /* show modal promotion window */
var promise = new Promise((resolve) => { _promote = resolve });
await promise.then((result) => { type = result });
if (type === undefined) type = "Q";
(...)
}
So after creating the promise, the program will wait until the popup window resolves it. The popup window resolves the promise as follows when it is closed:
_promote(type); /* resolve promotion-promise */
N.B. Please keep in mind that in this case the promote_piece() function itself also has to be called with the "await" keyword! Otherwise the program will execute it asynchronously and continue anyhow
You need to break your function at that point, and add another function to catch the user's button press event.
You can use Narrative Javascript to introduce blocking behavior and simplify it (so you don't need to break up your function into two part), but note that this library has been abandoned since 2013.
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