Details regarding the enthusiastic execution of Promise callbacks

Is there a specific specification or implementation detail that dictates how quickly the callbacks of a promise are evaluated? For example, if I have:

var promise = new Promise((resolve) => {
   resolve()
});

console.log(promise); // there is no public field '<state>', but you can see it in the console of the dev tools

I notice that the promise is already fulfilled immediately. I expected that the Promise would wait to call the resolve callback at a later time, leaving a "time window" where the promise remains unfulfilled.

Is this quick evaluation of the resolve callback intentional design, or is it simply an implementation detail?

Answer №1

When the Promise constructor is used, the callback provided to it is executed synchronously by the constructor itself. This means that by the time the constructed object is returned by the `new` operator, the callback has already been run.

This behavior is specified in the ECMA Script documentation. The steps for creating a new Promise in new Promise(excecutor) outline that the executor function is called first (step 9) and then the promise object is returned (step 11).

The folks at Mozilla provide this information in their documentation:

Syntax

new Promise(executor)

Parameters

executor

The executor parameter refers to a function that should be executed during the process of constructing a new Promise object.

Typically, the callback function in the constructor is utilized to begin an asynchronous operation (using functions like `setTimeout`) that will eventually resolve the promise even after the callback has finished executing.

function executor(resolve) { 
    setTimeout(resolve, 100);
}

var promise = new Promise(executor);

In some cases, such as the example given, the callback directly invokes the `resolve` function synchronously instead of using an async API. This results in the created promise being fulfilled immediately when assigned to the `promise` variable.

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

Transferring PHP objects to JavaScript arrays

I have been searching for a unique JS array of PHP arrays with a specific format. After hours of research and attempts to use the json_encode PHP function, I still haven't achieved the desired format. Here's an example of what I'm looking fo ...

Steps for positioning one div below another:1. Set the position property

Indeed, I am aware that this question has been asked numerous times in the past. Despite trying other solutions, none seem to resolve my issue. My objective is to have the "register" div slide down beneath the "container" div, rather than appearing next t ...

Ways to access a clicked element using AngularJS with ngClick

I am attempting to dynamically add a class to an element when it is clicked using AngularJS. The element is generated through ngRepeat, and I need to determine which specific element was clicked by utilizing the ng-click="foo()" directive. Here is a snipp ...

Is there a solution to successfully retrieving the value of res from the readCsv() method instead of it returning undefined?

In this scenario, I have a file uploader that accepts .json and .csv files. When the upload button is clicked, the HomeComponent calls the service dataparser which has two functions: readJson and readCsv. One function returns an observable while the other ...

Backand - How can I display the contents of variables using console.log() within Security Actions?

Is there a way to utilize console.log() in Backand, specifically within the server side functions like those found under Security & Auth > Security Actions? I have checked the Read.me which suggests using 'console.log(object) and console.error(obje ...

Loop through an array of JavaScript objects, compare a specific value within each object with all others to ensure uniqueness, and then add the unique objects to a new array

What is a efficient method to iterate through a JavaScript array of objects, and within each object, verify the uniqueness of a specific value compared to all others before adding it to a new array. Here is the sample array of objects: const weatherArray ...

What is the best way to conceal a modal using jquery?

Click button to open modal: <button type="button" class="btn" onclick="CountClass()" runat="server" data-toggle="modal" data-target="#inlineForm1">OPEN</button> The modal code: <div class="modal fade text-left" id="inlineForm1" tabindex=" ...

Decide whether to execute a promise or not, and then pass the resulting value to another promise

Struggling to find a way to write the following code without nested promises. function trickyFunction(queryOptions, data) { return new Promise((resolve, reject) => { if (data) { resolve(data); } else { // ... various conditions t ...

Linking a jquery modal popup script to a button click event

I have implemented a basic jQuery script called bPopup () to display a modal pop on a .net web form. As someone new to jQuery, I am encountering an issue where the modal pops up before the codebehind event tied to the button click is executed. The modal co ...

Creating interactive tables in JavaScript with dynamic row adding, editing and deleting capabilities

Whenever I try to add a new row by clicking the Add Row button, an error occurs. My goal is to append a new 'tr' every time I click the add row button. Each 'td' should include a checkbox, first name, last name, email, mobile number, ed ...

perform action following a $router.go in Vue

Looking for guidance on how to properly execute a function after navigating back using this.$router.go(-1). I attempted using nextTick, but it doesn't seem to be the right approach. Any suggestions? ...

The consistent index is shared among all dynamically generated elements

I'm currently working on a project where I am generating dropdowns within a table dynamically. I am attempting to determine the index of the dropdown that triggered the event in the following way: $(".template").on('change', '.dataType ...

Setting limits to disable or remove specific times from the time picker input box in Angular

I'm having trouble with a time input box. <input type="time" min="09:00" max="18:00" \> Even though I have set the min and max attributes to values of 09:00 and 18:00 respectively, it doesn't seem to be working properly. I want to ...

Is it possible to utilize a standard button for sending data and triggering a JavaScript function in either JavaScript or PHP?

Recently, I created a function where clicking a button rotates an image. Now, I am looking for a way to specify the number of degrees for rotation using a text field. Additionally, I want to integrate a PHP function that controls a stepper motor alongsid ...

When a certain condition is met, the function can be stopped using clearInterval

Is there a way to stop the setInterval function if a specific condition is met in my code? Here is the code snippet: var checkRecordlock = function() { jQuery.ajax({ url: "http://localhost/project/crl/Mzk=" }).done(function(data) { var is_loc ...

Executing an ajax request following validation

I am facing an issue with my ajax insert script and validation script. Currently, the insert script is executing regardless of the validation result. How can I modify my code to ensure that the insert query only runs after successful validation? Below is ...

Guarantee the successful execution of a server-side function using my client-side function

I am currently in the process of creating a website that utilizes Javascript and Asp.net. My code contains numerous functions on the client side, within my html code, while my server side functions are called using a webservice. How can I ensure that my c ...

Discovering techniques to minimize the need for prop drilling in ReactJS component trees

As I was reading through the ReactJS documentation, I stumbled upon the section about Contexts where I found the following information: The page mentioned that if you only need to avoid passing certain props through multiple levels, using component compo ...

Refine the Vuex state with a filter

Currently, I've progressed in my Vue development journey and started exploring the implementation of Vuex for state management. In the past, I had a main Vue component that handled search functionality, an array of items to iterate over, and the iter ...

What is stopping TypeScript from assigning certain properties to the HTMLScriptElement?

I'm currently working with TypeScript and React, and I'm facing an issue with a function that is meant to copy script attributes between two elements: type MutableScriptProperties = Pick< HTMLScriptElement, 'async' | 'crossO ...