Here is a snippet of code to consider...
const array = [
Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)
];
Array.prototype.then = function () {
console.log('Why is this triggered?');
}
Promise.all(array)
.then(result => console.log(result))
Why does the Promise.all()
method automatically call the custom .then()
prototype function on the Array?
It's expected that .then()
would be called for each element in the array, but why is it also being triggered on the Array itself?
This behavior specifically occurs on V8 engines.
Important note: If you switch from using Promise.all()
to Promise.race()
, this behavior does not occur.
I'm not suggesting this is an error. I simply want to comprehend the reasoning behind it. It would be greatly appreciated if reference to the EcmaScript specification could be provided in the response.
Update:
I am aware that Promise.all()
ultimately returns an array wrapped in a promise. This fact is clear. Even if you omit the .then()
like so...
Promise.all(array)
the .then()
method still gets executed.