2

Today I was trying excersice from a book, need to simulate Promise.all. My code now looks like this

async function Promise_all(promises) {
    let result = [];
    for(let promise of promises) {
       let resolvedPromise = await promise;
       result.push(resolvedPromise);
    }
    return result;
}


function soon(val) {
  return new Promise(resolve => {
    setTimeout(() => resolve(val), Math.random() * 500);
  });
}

And there one interesting thing call:

     Promise_all([Promise.reject(1), soon(2)])
.then(array => console.log('Array:', array))
.catch(error => console.log('Error:', error));

works fine, as I expected, but with call:

    Promise_all([soon(1), Promise.reject(1), soon(2)])
.then(array => console.log('Array:', array))
.catch(error => console.log('Error:', error));

I always get UnhandledPromiseRejectionWarning. Can somebody tell why this is hapenning? I also tried exception handling, but it didn't fix this problem. Thank you in advance.

Ofir Baruch
  • 10,323
  • 2
  • 26
  • 39
abychutkin
  • 21
  • 2
  • 2
    You're not handling the rejected promise until you `await` it after one second of waiting for the first promise. `async`/`await` cannot simulate `Promise.all`, you'd need to use the `new Promise` constructor. Implementing error handling for it is hard. Does the book exercise offer a solution? – Bergi Jan 14 '21 at 22:23
  • Answer to this excersice - https://eloquentjavascript.net/code/#11.2 I thought that await here would be better, because I thought that promises would be resolved one after another and delay in previous promises won't affect next promises – abychutkin Jan 14 '21 at 22:42
  • 1
    `await` does not "resolve" a promise. A promise resolves on its own (depending on how it was created), all you can do is to wait for it. If you get an array of promises, you must assume that they fulfill/reject in any order. – Bergi Jan 15 '21 at 08:23
  • But I still don't understand why rejected promise gives warning only then it goes in array after resolved promise in array. First we wait till promise would be resolved or rejected and after that we get to rejected promise as I understand. – abychutkin Jan 15 '21 at 09:06
  • 1
    Yes. The problem is that in your code, you are getting to the rejected promise *too late*. In the meantime it was already reported as an unhandled promise rejection. You could (should) have handled it (by rejecting the `Promise.all` result promise) immediately. – Bergi Jan 15 '21 at 09:12
  • So Promise.reject() immediately reports as unhandled promise and I don't get warning only when rejected promise first in array and handled at the same time as it was rejected. @Bergi thank you for your answers. – abychutkin Jan 15 '21 at 09:47

0 Answers0