The sequence of synchronous execution within a Promise

I encountered a problem while attempting to test a Promise within an event listener. Although everything seems to be working fine, the execution order is not as expected.

var test = document.querySelector('#test');
test.addEventListener('click',function(){
    Promise.resolve().then(function(){
        throw 'first';
    }).catch(function(er){
    console.log(er);
    });
});
test.addEventListener('click',function(){
    console.log('second');
});
test.click();
<div id="test"></div>

Can someone explain why the second listener is finishing before the first listener?

Answer №1

It adheres to the standard requirements in the following manner:

  1. If the promise's [[PromiseState]] internal slot holds the value "fulfilled",
    a. Set the value as the promise's [[PromiseResult]] internal slot.
    b. Add the task
    EnqueueJob("PromiseJobs", PromiseReactionJob, «‍fulfillReaction, value»)
    .
  2. Or if the promise's [[PromiseState]] internal slot holds the value "rejected",
    a. Set the reason as the promise's [[PromiseResult]] internal slot.
    b. Add the task
    EnqueueJob("PromiseJobs", PromiseReactionJob, «‍rejectReaction, reason»)
    .

Therefore, when a promise is resolved or rejected, a corresponding callback is scheduled to run asynchronously at a later time, separate from the current execution.

References:

Answer №2

The first and second listeners operate independently, working asynchronously without relying on each other. Why segregate them when you can streamline the process with the code snippet below?

    Promise
        .resolve()
        .then(function(){
            throw 'first';
        })
        .catch(function(error){
            console.log(error);
        })
        .finally(function(){
            console.log('second');
        });

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

Transforming Child_process.spawn's "Promise" syntax into "async/await" syntax.---Here's how you can convert the syntax of Child_process.spawn from using

Trying to wrap my head around the async/await syntax, I have come accross a code snippet that intrigued me. The following is the Promise-based version of the code: function callToolsPromise(req) { return new Promise((resolve, reject) => { l ...

Positioning the close button on the top right edge of a Material-UI Dialog: A step-by-step guide

https://i.sstatic.net/ARTtq.png How can I include a close icon in the top right corner of the header section? I'm using the Material UI Dialog and everything works well, but I need a close button in the top section. Can anyone assist me with this? ...

The function this.someFunction does not exist

Even though I have gone through the details of the bind requirement for methods to be associated with a React ES6 class, I am still facing challenges with this specific example: class ProductList extends React.Component { constructor(props) { super( ...

Using AngularJS to bind a dynamically created form built in JavaScript

I am looking to dynamically build a form using JavaScript and utilize it within an AngularJS form controller. In the example provided below, the form is not rendering as HTML, and I aim to bind it to the model variable. http://jsfiddle.net/g6m09eb7/ ...

Is there a Facebook application embedded in the user's wall?

Is it feasible to create a website similar to YouTube, where users can share it on Facebook and run the app (in this case, the video player) directly on their wall without having to visit the YouTube page? If it is possible, is this functionality limited ...

Is it possible to eliminate the dedupe feature in npm?

By mistake, I accidentally ran the command npm dedupe and now all of my node_modules directories are flattened. While this reduces file size, it's making it more difficult to find things. Is there a way to reverse this and return to the hierarchical f ...

Perform a calculation using data from one schema and store the result in a different schema within MongoDB using Node.js

var ItemSchema = new Schema({ name: {type: String}, size : {type: String}, price : { type: Number} }); var SizeSchema = new Schema({ sizeName: {type: String}, dimensions : {type: String} }); F ...

#Error 500 encountered in a basic Ruby on Rails and AngularJS collaboration

Thanks to everyone for taking the time to assist me with this problem. As a newcomer to Ruby, the solution may be quite simple. I have developed an API that facilitates communication between Ruby and Angularjs. Here is the API: class EntriesController < ...

Nested function and the process of breaking out of the parent function

Is it possible to exit out of the main/parent function when I am in a function that was called from inside another function? For example: function(firstFunction(){ //stuff secondFunction() // code continuation if second function doesn't ...

issue with duplicating DOM element using function

My situation is unique from the one described in this post. The code mentioned there is not functioning as expected when clicking the clone button. I have even provided a video explanation of how that code works. Unfortunately, I haven't received any ...

Tips on Handling Multiple Versions of jQuery

I'm seeking your guidance on a particular issue at hand. I am part of the development team for a large web application that heavily relies on jQuery and has been in constant development for the past 7-8 years. Over this time, several versions of jQue ...

Steps on how to set the values of a select option based on a JSON parsed array

After receiving an array from a JSON call, I am trying to populate a select element with the data. {1:Android, 2:IOS, 3:Business Management Systems, 4:Database, 5:Codes/Scripts, 6:Others} or 1: "Android" 2: "IOS" 3: "Business Management Systems" 4: "Da ...

Is there a way to eliminate the 'All Files' option from an HTML file input field?

I have implemented a feature to allow users to upload custom files using . Currently, I am restricting the allowed file types to only ".Txt, .SVG, .BMP, .JPEG" by using accept=".Txt,.SVG,.BMP,.JPEG". This setting causes the browser's file-select dial ...

Utilizing useQuery() with API route parameters in Nuxt 3: A Step-by-Step Guide

I've been following a tutorial on building api routes and the process is as follows: 1. Start by creating a new file called server/api/route.js: export default defineEventHandler((event) => { return { message: `hello api route` } ...

Identifying the moment when the hide() function in jQuery is triggered for an element

Is there a way to detect when the .hide() method in jQuery is triggered on an element? I attempted to attach an event listener to the hide event of that particular element: $('div').bind('hide', function(){ alert("Hidden&q ...

Modifying the DOM within a getJSON callback

My current challenge involves fetching data from the YouTube API and displaying it on my website. However, I am facing an issue where the DOM changes made inside the getJSON's callback function are not reflecting on the webpage. Even though I can see ...

"Upon choosing a file using the HTML input file multiple element, a triggered event

After selecting multiple files using the input type="file" HTML element, I am eager to start uploading them. Can you tell me which event I should use to execute code immediately after finalizing my file selection? This is what my HTML code looks like: &l ...

Tips for concealing the body description on the homepage of a blogger website

I want to conceal this description This is my blog and I am facing an issue where I need to hide the description on the home page. I have tried using color:white which worked initially, but when I moved the description to the top or left, the black backgro ...

In the present technological landscape, is it still considered beneficial to place Javascript at the bottom of web pages?

As a beginner in web programming, I've recently delved into Javascript. A hot debate caught my attention - where should javascript be placed, at the top or at the bottom of a webpage? Supporters of placing it at the top argue that a slow loading time ...

What is the best way to stream an app's data directly to a browser in real time?

My node application is currently able to read a stream from a Kafka producer and display it in real time using console.log. However, I would like to update my web application with the same real-time functionality. How can I achieve this? I typically start ...