1

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...

Sara Ree
  • 3,417
  • 12
  • 48

2 Answers2

0

First you can store all not resolved results of all this methods in array and then you can use Promise.all(). It will resolve all promises inside this array. If any of this promise will return error then none promise of this array will be resolved.

let results = [];
for(let i = 0; i < guidePack.length; i++){ 
      results.push(Proceed(guidePack[i]));
}
Promise.all(results)
 .then(...)
 .catch(...)
Krzysztof Kaczyński
  • 4,412
  • 6
  • 28
  • 51
0

We can use Promise.all or Promise.allSettled functions for more info have a look at

Differences between Promise.all() and Promise.allSettled() in JS?

Ziaullhaq Savanur
  • 1,848
  • 2
  • 17
  • 20