I know if we have an async-await promise inside a for loop like this it will await for resolving the Proceed
function on each of the iterations and after the last one we can see the log below the for loop:
for(let i = 0; i < guidePack.length; i++){
await Proceed(guidePack[i]);
}
console.log("after for loop"); // we will see this only after all of the Proceeds are resolved
What I don't know is if there is a solution to resolve all the promises at once and leave the for loop to see the console log below it?
Let's have a look at the code I'm talking about:
let guidePack = ['A', 'B', 'C'];
let ProceedResolved;
guide(); // initiate proccess
async function guide() {
StartCaptureKeyPress();
for(let i = 0; i < guidePack.length; i++){
await Proceed(guidePack[i]);
}
console.log('Guide is resolved!');
}
// this function executes speaker function, at speaker function we will resolve the promise
function Proceed(e) {
console.log(e); // log A and B and C
speaker();
return new Promise((resolve) => {
ProceedResolved = resolve; // resolve the Proceed when ProceedResolved() executes
});
}
function speaker() {
// resolve proceed after 6 seconds
setTimeout(() => ProceedResolved(), 6000);
}
// Capture 'Enter Key' press
function StartCaptureKeyPress() {
document.addEventListener('keydown', onKeyDownCapture);
function onKeyDownCapture (event) {
if (event.keyCode == 13) {
console.log('Enter Key Pressed')
document.removeEventListener('keydown', onKeyDownCapture);
event.preventDefault();
for(let i = 0; i < 2; i++){ ProceedResolved(); } // resolve promise here
}
}
}
if you don't touch anything it will log the guidePack
elements one after another. and after them, you can see the console log saying Guide is resolved!
. like this:
"A"
"B"
"C"
"Guide is resolved!"
if you press Enter key on your keyboard I want to resolve all remaining promises and leave the for loop to see the console log Guide is resolved!
. So if after "A" log you press the Enter key we should see this:
"A"
"Enter Key Pressed"
"Guide is resolved!"
I have tried to execute resolve multiple times but it doesn't work. I can't do this without a hand please help...