What is the expected result of running this Javascript program with asynchronous tasks?

My expectation with this code is that it will run, then after a 2-second delay, the execution stack will become empty with one callback in the setTimeout function. Since the promise is not resolved yet, I anticipate both the message queue and job queue to be empty at this point.

Based on my understanding, the Callback should be printed first, followed by the resolution of the promise after 3 seconds - printing the message "Promise is resolved". However, the actual output differs from my expectations. What am I overlooking here?

Here is the code snippet:

setTimeout(function() {
    console.log("Callbcack");
}, 0);
 
new Promise((resolve, reject) => {
    console.log("Inside promise");
    let ms = 5000 + new Date().getTime();
    while (new Date() < ms) {}
 
    resolve("Promise is resolved");
 
}).then((data) => {console.log(data)})
.catch((err) => {
    console.log(err);
})
 
var ms = 2000 + new Date().getTime();
while (new Date() < ms) {}

Answer №1

When you initiate a new Promise with an executor function, the promise executor runs synchronously, meaning it is processed immediately when called (new Promise(executor)). This results in the promise being resolved during the top level code execution (within the initial stack) after a delay of 5000 milliseconds.

Following that, the microtask queue is invoked, leading to the output of console.log(data).

Subsequently, JavaScript's event loop is then able to handle the next asynchronous task, which in this case happens to be the timer handler.

Answer №2

Uncover the world of JavaScript's microtasks that operate with two distinct callback queues. There is one queue for microtasks and another for macrotasks. When dealing with a Promise, its callback is treated as a microtask, while callbacks from setTimeout function as macrotasks. The sequence in which these queues are handled prioritizes microtasks over macrotasks.

Even if you schedule

function() { console.log("Callback"); }
before
(data) => { console.log(data) }
, the latter will always be executed first no matter how long the thread is blocked prior to resolving the Promise. This is because both queues are processed only after the top-level code execution is complete.

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

Is there a way to disable the useMutation function once it has successfully completed its

Greetings, I am facing an issue with the mutation below: export const useUserSearch = (data) => { return useMutation({ mutationKey: ["user-search", data], mutationFn: fetchUser, }); }; I have implemented it in my component as foll ...

Verifying a checkbox selection within an Autocomplete feature using MUI

[ { label: 'First', checked: false }, { label: 'Second', checked: true } ] Here is a brief example of how the data may be structured. I am utilizing Material UI's Autocomplete feature to enable searching based on labels. Thes ...

How should I position <script> tags when transferring PHP variables to JavaScript?

I've attempted to find an answer without success due to its specificity. Within the header.php file, which serves as the header of the website, various scripts are included to enable jQuery functionality. Additionally, there is a file called workscri ...

How can you determine the location of a point on the perimeter of a regular polygon?

Imagine you have a pentagon, with numbered sides like moving around a clock: https://i.sstatic.net/pWqdFtfg.png Starting from the center of the polygon, how can you calculate the position of a point in these locations (along the edge of the polygon): At ...

Convert time display to a 24-hour format using JavaScript

I managed to convert the time format from GMT to my browser's local time using the following JavaScript code: var newDate = new Date(timeFromat); timeFormat = newDate.toLocaleString(); Now, I want to change the time format to a 24-hour clock format ...

Mastering intricate string manipulation using JavaScript regular expressions

I have a JavaScript/Node JS program that generates meaningful names according to the following rule: Input: "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId" Expected output: "TenancyAccountAcco ...

How does the Paginate Pipe effectively retrieve the array length in an Angular 2 application?

I find myself in an interesting situation where I have a piece of code that is functioning within my Angular 2 application - it's generating the correct value, but the method behind its success is unclear to me. Specifically, I am using ng2-paginatio ...

When attempting to access localhost:3000, the React/NodeJS web page fails to load

As a new developer working with React and NodeJS, I am eager to dive into these technologies: React for the client-side NodeJS for the server-side Webpack for building my files Here is the structure of my project: my-application/ webpack.s ...

What could be the reason for the cardDetails component, which is supposed to display information received via a Vuex action, not appearing

Recently, I've been diving into Vue and Vuex while working on a small app that showcases events. Users can click on event cards to view more details using the card's ID. I've moved all the code to the Vuex Store, but I'm encountering is ...

Combining Data in Django using Ajax with JavaScript and Python Integration

I am in need of assistance understanding a basic ajax call from JavaScript to Python. I have a Python function that takes a simple parameter and returns a result. My goal is to send this parameter from JavaScript, receive the function result back in JavaSc ...

Request the generic password prior to revealing the concealed div

I want to implement a feature where a hidden div is shown once a user enters a password. The password doesn't need to be stored in a database, it can be something simple like 'testpass' for now. Currently, I have written some code using Java ...

What is the method for displaying map tooltips by default rather than on mouseover?

Currently, I have a script set up to display a map with two markers. Whenever I hover over one of the markers, a popup tooltip appears with location information. My question is, how can I make the information appear by default without needing to hover ov ...

Dealing with errors in node.js without duplicating response headers

I'm finding myself a bit perplexed by the req, res parameters in node and how to properly manage them when dealing with asynchronous calls. One of my functions is intended to add an Item to my DB, update some DB models accordingly, and then send a suc ...

Utilizing Zoomdata data in conjunction with echarts index.js to create a dynamic stacked line chart

I am currently working on integrating Zoomdata with an echarts javascript chart to visualize data from 20 different computers in a stacked line chart format. While I can manually code this setup, I am looking for a way to dynamically link the data from Zoo ...

Next.js experiencing development server compile errors and broken page routing in production builds

Howdy everyone! I'm currently working on an app using Next.js. Every time I make a change, the server automatically compiles with the updates, but unfortunately, the pages often fail to render properly. Sometimes it takes several minutes for them to l ...

Issue: Trouble with ajax form functionality

I'm a beginner in ajax, js, and php. Recently, I set up a simple contact form. <form id="contact-form" method="post" action="process.php" role="form"> <div class="messages"></div> <div class="form-group"> <l ...

How to Load and Parse CSV Files in Meteor.js

What is the best approach for reading CSV files into a Meteor app from a filesystem path located within the /private directory? I came across the fast-csv package, which is also available as a Meteor package. However, I am unclear on how to create a creat ...

Accordion content from MUI gets cut off by bookmark bar when expanded

How can I prevent an MUI accordion in an appBar from moving up and hiding behind the browser's bookmark bar when expanded? const useStyles = makeStyles((theme)) => { appBar: { borderBottom: "2px solid #D2D2D2", backgro ...

Unexpected Error with Background Position Variable

Hello, I am attempting to create an animated background effect that moves up and down using the .animate() and .hover() methods in jQuery. Within my DOM, there is a div with id="#menu" containing a UL list where each item has a background positioned at dif ...

Discovering the method to retrieve a previous month's date within a VueJs application using Javascript

Can someone guide me on how to retrieve the date of the past month using Vue? This is the code I currently have: import SomeTable from "./table/SomeTable"; export default { name: "Cabinets", components: {SomeTable}, data() { return { ...