Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Promise.all() tigger Array.prototype.then if defined?

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.

like image 624
Iván Sánchez Avatar asked Jan 06 '20 16:01

Iván Sánchez


1 Answers

When a resolve() is called, and the value passed to it has a .then property that refers to a function, the normal Promise mechanism will invoke that function. In this case, internal to Promise.all() an array of resolution values is built as each Promise in the source array is resolved. When that finishes, the innards of Promise.all() will call its own resolve(), passing in the array of resolved values.

Well that array will also have a .then() value, inherited from the Array prototype. Thus that resolve() call will invoke the .then() method just like any other Promise resolution would.

Promise resolve() in the spec

like image 108
Pointy Avatar answered Sep 29 '22 23:09

Pointy