What is the reason for Promise.all() causing Array.prototype.then to be executed if it is defined?

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.

Answer №1

Whenever a resolve() function is triggered, and the value being passed to it contains a .then property which points to a specific function, the usual Promise process will execute that function accordingly. Inside the scope of Promise.all(), a series of resolved values are accumulated in an array as each Promise within the original array gets resolved. Once this process is completed, the inner workings of Promise.all() will invoke its own resolve(), supplying the resulting array of resolved values.

This resulting array will also contain a .then() attribute, inherited from the Array prototype. Therefore, the invocation of the resolve() function will trigger the execution of the .then() method just like any other scenario involving Promise resolution.

Check out the Promise resolve() section in the specifications for more information

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Condense an Element Using Position: Absolute

https://i.sstatic.net/GMUss.png I'm attempting to create functionality where the "Open Chat" button displays an Absolute positioned div, then hides it when clicked again. I experimented with using the react-collapse component, but encountered issues ...

The Ajax operation does not finish before the second one is initiated

My Ajax function is set up like this: function PersonAtlLawUpdate(personRef) { var selectionPanel = $('div#SelectionPanel'); var fromdate = selectionPanel.find('input#FromDateTextBox')[0].defaultValue; var timeSpan = selectionPanel.fin ...

What steps can I take to ensure that the content remains intact even after the page is

Hey there, I hope you're having a great start to the New Year! Recently, I've been working on creating a calculator using HTML, CSS, and JavaScript. One thing that's been puzzling me is how to make sure that the content in the input field do ...

What steps should I take to pinpoint the fundamental mistake in my webpage dedicated to clocks?

Exploring an intriguing clock project that utilizes ancient timekeeping methods found at . Recently encountered a puzzling error in Chrome, where it claims to be unable to call a method on undefined. Strangely enough, the error message is not located near ...

Tips for managing errors in HTTP observables

I'm currently facing a challenge with handling HTTP errors in an Angular2 observable. Here's what I have so far: getContextAddress() : Observable<string[]> { return this.http.get(this.patientContextProviderURL) .map((re ...

Exploring Laravel's method for retrieving data from multiple tables in the controller

In an effort to make my jQuery call more dynamic, I have a controller with the following method: public function api(Request $request , $project_id){ return Program::where('project_id',$project_id)->get(); } This results in: [{"id":178," ...

Avoiding Multiple Clicks on Anchor Tags in AngularJS

After implementing the sharing functionality, I have noticed that it works fine but there is a repeating issue with the user list. Every time the 'a' tag is clicked multiple times, the user list gets repeated. Can someone guide me on how to resol ...

Retrieving customData from fullCalendar JSON in the dayClick event handler

Apologies for what may be a simple question. I am trying to insert some custom JSON data into the fullCalendar plugin and utilize it within my dayClick callback function. Specifically, I aim to access and modify elements in customData when a day is clicked ...

Transform Client - Server command-line interface Node.js application into a Docker container

My Node.js application consists of two separate components: an Express.js server and a CLI built with vanilla JavaScript and inquirer.js. These components communicate with each other through a REST API. The main reason for this setup is to adhere to the SO ...

What steps should I follow to modify the code in order to specifically choose the user inputted into the system?

I am facing an issue while trying to login and make a request. The function is currently checking only the first element from my users database. I need help in modifying the code so that it selects the user based on the input provided by me. router.post ...

hiding the refusal of the response to return - nodejs

I am completely new to using Node.js and promises. Recently, I have been working on calling an API from the client-side with the following code: return dbNameses.checkNamesAvailable(request.body.data.attributes.Names) .then((results) => { if(resu ...

Pausing and resuming JavaScript incrementation at specific junctures

I am working with two sets of <ol> (ordered list), and I want the numbering to reset at the last <li> in each list. My objective is to restart the numbering when it reaches the end of each set of <ol>. For instance, if you visit the Fidd ...

Is it possible to incorporate personalized JavaScript alongside bootstrap?

Just recently started using bootstrap and was curious about something. Can custom JavaScript be integrated with bootstrap buttons without any additional adjustments? ...

Attempting to troubleshoot the issues causing my React application to malfunction

Having some trouble with my Spotify project. Every time I search for an artist, I receive an error message saying "illegal redirect_uri." I am also facing a list of coding issues that I am struggling to resolve. Any advice or suggestions would be greatly a ...

Guide to placing the cursor at a specified position within an editable content div

I am struggling with a div <div id="user_status" class="status expanddiv" onkeyup="username_Search('New','user_status');" contenteditable="true" data-text="What's on your mind?..."> Some Text will be inserted here. </div ...

Using a single package manager for both backend and frontend development - is it possible? (Yarn/NPM)

Before, I relied on NPM for server-side tasks and Bower for frontend. NPM would install packages in the node_modules/ directory, while a .bowerrc file directed package installations to public/lib. Recently, I've made the switch to Yarn from NPM, and ...

Changing the font family for a single element in Next.js

One unique aspect of my project is its global font, however there is one element that randomly pulls font families from a hosted URL. For example: https://*****.com/file/fonts/Parnian.ttf My page operates as a client-side rendered application (CSR). So, ...

Enabling communication between JavaScript and PHP and vice versa

I am currently working on developing a Firefox plug-in with the purpose of gathering all the domains from the links located on the current site and showcasing their respective IP addresses. In order to achieve this, I have written JavaScript code that incl ...

What is the best way to embed MongoDB queries in Node.js?

I have a group of users with the following details: { "_id" : ObjectId("56f60e4eea8af4670408483e"), "twitterHandle" : "shrutip", "firstName" : "Shruti", "lastName" : "Patil", "emailID" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

The div on my webpage is not loading its content as expected when using JavaScript

I am having trouble continuously loading the content of a div from another page. Using alert worked fine, but the page data is not loading. JavaScript <script> $(document).ready(function(){ setInterval(function(){$("#loadAvailable").load("update.p ...