Having the following pice of code...
const array = [
Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)
];
Array.prototype.then = function () {
console.log('Why does this gets triggered?');
}
Promise.all(array)
.then(result => console.log(result))
Why does Promise.all()
by itself calls my .then()
proto function on the Array?
Of course it must call .then()
for each of the elements in the array. That’s obvious. But what is the purpose of doing it over the Array itself?
This behavior is happening on V8
To consider: If you change Promise.all()
to Promise.race()
this does not happen.
I'm not saying this is a mistake. I just want to understand the reason. If you can quote the EcmaScript specification on the answer I would really appreciate.
Update:
I know Promise.all()
returns an array but wrapped on a promise. That is obvious too. If you remove the .then()
like...
Promise.all(array)
it still executes the .then()
method.