2

I'm having a hard time trying to stop the loop in promise.all if one promise rejects it. Here's how I did it. Is there something wrong with this?

 Promise.all(myArray.map((obj) => {
      this.someFunction(obj);
 }))

Here's the function I call..

someFunction(){
 return new Promise(function (resolve, reject) {
    ....
     reject()
 })}
mingmingming
  • 345
  • 2
  • 4
  • 12
  • 1
    [`Promise.all` does not "loop" anything](https://stackoverflow.com/a/30823708/1048572) – Bergi Nov 22 '18 at 13:24
  • The map returns an array and it is created "instantly", `Promise.all` will resolve if all promises in the array are resolved and will reject if one rejects. What exactly are you trying to achieve? – koox00 Nov 22 '18 at 14:54

2 Answers2

0

I have updated my code, it is tested and it works on my machine with the mock data I feed it with. I am not exactly sure how the rest of your code is structured but it is something likes this: Oh and you cannot break out of a map, but we will use a simple for loop because we can break out of that:

function someFunction(){
 return new Promise(function (resolve, reject) {
      // I will be rejeccting a boolean
      // If you are resolving something, resolve it as true
     reject(false)
 })}


async function shouldStopLoop(){

  // the boolean will come here
  // if it is false, the catch block will return
  // if it is true, the try block will return

  let stopLoop = null;
  let result = null;

  try {
     result = await someFunction();
     return result
  } catch(error) {
    stopLoop = error;
    return stopLoop;
  }
}

function mayReturnPromiseAll() {

  let myArray = ['stuf to loop over...']
  let arraytoGoInPrimiseAll = [];


  // Array.prototype.map cannot be stopped
  // Thats why we will use a for loop and we will push the data we need
  // into another array 
  for (var i = 0; i < myArray.length; i++) {
    if (!this.someFunction(obj)) {
        break;
    } else {
      // push things in arraytoGoInPrimiseAll
    }
  }

  if(arraytoGoInPrimiseAll.length > 0){
    return Promise.all(arraytoGoInPrimiseAll)
  } else {
    // do something else
  }

};
squeekyDave
  • 918
  • 2
  • 16
  • 35
  • still works the same. I'm expecting to stop the loop once the promise encountered rejection. Is there a way for this? – mingmingming Nov 22 '18 at 12:52
0

Try this:

const arrayOfFunctions = myArray.map(obj => this.someFunction(obj))
Promise.all(arrayOfFunctions).then(values => {
 console.log(values);
}).catch(error => {
  console.log(error)
});
Diamant
  • 112
  • 1
  • 10