'Using two awaits in javascript function both call the same function to create a promise, program waits for first await but not second
I have created some alert/prompt popup boxes with await, async, and a promise. To display the popup box, I call the function to create the promise which also creates the popup box. The first time the function to create the popup box is called, everything works beautifully. However, the second time, the code does not wait for the result of the popup box but instead keeps executing.
I of course want the code to wait for the second call to ddaprompt() to finish before continuing, but it doesn't.
I suspect it has something to do with using the same function to create two promises or it's almost like the second time the promise function is called, it's duplicating the first promise along with the fact that it's already resolved and therefore returns right away, or perhaps it's with the sequence of function calls to get to where the promise is created. But I don't know.
Note that there are some regular javascript alert boxes that say what is happening.
async function ddaconfirm(content, addtxtbox, txtfrtxtbx) {
var ddalertinterval;
var promise = new Promise((resolve, reject) => {
ddaalert(content + "<br style='line-height: 34px;'>" + ((addtxtbox) ? "<INPUT TYPE='text' id='USRRSPNSE' value=" + txtfrtxtbx + "><p></p>" : "") + confirmbuttons);
if (addtxtbox) document.getElementById('USRRSPNSE').focus();
ddalertinterval = setInterval(function confirmresult() {
if (buttonpressed != undefined || document.getElementById('POPUPBX').style.display == 'none') {
if (buttonpressed == true && addtxtbox) buttonpressed = document.getElementById('USRRSPNSE').value;
resolve(buttonpressed);
}
}, 100);
});
var result = await promise; /* wait until the promise resolves*/
clearInterval(ddalertinterval);
// ddaalert(result + " From Promise!"); // "done!"
return result;
}
async function ddaprompt(content, defaulttxt) {
return await ddaconfirm(content, true, defaulttxt);
}
async function testprompts() {
var positiontoadd = await ddaprompt("Enter the number of the position of the column to add. Enter a number between 1 and <somenumber> " , "") -1;
alert(positiontoadd);
var texttoadd = await ddaprompt("Enter the title the new column should have, use CAPITALS, and a unique set of letters:", "");
alert(texttoadd + "Didn't wait for second ddaprompt to finish");
}
testprompts();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
