Sequencing and fulfillment of promises in a job queue using Promise.race

Currently, I'm grappling with the concepts of job queue and promise resolution in Javascript. While going through Nicholas Zakas' book "Understanding ECMAScript 6", I came across a code snippet regarding Promise.race() that has left me puzzled:

let p1 = new Promise(function(resolve, reject) {
    resolve(42);
});

let p2 = Promise.reject(43);

let p3 = new Promise(function(resolve, reject) {
    resolve(44);
});

let p4 = Promise.race([p1, p2, p3]);

p4.catch(function(value) {
    console.log(value);     // 43
});

In this scenario, p4 is rejected due to p2 already being in a rejected state when Promise.race() is invoked. Even though p1 and p3 are fulfilled, their outcomes are disregarded since they happen after p2's rejection.

My understanding is that Promise.race() resolves as soon as one of the provided promises is resolved. However, I am confused about why the book states that promise p1 settles after p2. If we follow the code from top to bottom, p1 comes first, so I would expect it to be settled first. Could this be due to the function wrapping, or is there something about Javascript execution order that I am missing?

Would appreciate it if someone could help clarify this concept for me.

Answer №1

It seems like the information in the book is inaccurate. In this case, p1 is completed before p2 is even created. When the example is run, the output is "42" instead of the expected "43" error message.

It's possible that the author misunderstood the behavior of the new Promise callback, which is actually synchronously invoked unlike other promise callbacks that use then. Perhaps the intended example was supposed to be

let p1 = Promise.resolve().then(() => 42);
//                              ^^^^^^^^ asynchronous
let p2 = Promise.reject(43);
let p3 = Promise.resolve(44);

let p4 = Promise.race([
  p1, // still pending
  p2, // already rejected
  p3  // already fulfilled
]); // hence, p4 will be rejected since the callback on p2 is the first to be invoked
p4.then(console.log, console.error);

Answer №2

I concur with Bergi's response. The promise constructor callback is called synchronously when you need to access the resolve/reject function outside of the constructor's scope. As shown in your code snippet, it is indeed executed synchronously. However, if the resolve/reject function is triggered by an ajax request or wrapped in a setTimeout function, the execution will then become asynchronous.

const p1 = new Promise((resolve, reject) => {
   setTimeout(() => resolve(42), 100); // resulting in an asynchronous process.
});

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

Utilize JQuery to modify hover state when focused and restrict tab navigation to specific areas on the keyboard

I'm currently working with a JQgrid in one of my projects (Check out the JFiddle here). and I have some specific requirements: 1.) I want the save & cancel button to become highlighted when a user tabs to it, similar to how it behaves on mouse ov ...

What could be the reason for the error message when using rs.send with a string input?

I'm a beginner in node and express, and I was trying to create an HTML form that takes two numbers and displays the result using "express" and "node". However, when I use rs.send(result), I encounter the following error: https://i.sstatic.net/FcUNJ.p ...

Socket.io encounters emitting issue within express app.post function

I am working on integrating an express application with a frontend React application using socket connections. My goal is to trigger an event on the connected socket whenever a post request containing JSON data is sent to my server. However, I am facing a ...

JavaScript and Angular are used to activate form validation

Update: If I want to fill out the AngularJS Forms using the following code snippet: document.getElementById("username").value = "ZSAdmin" document.getElementById("password").value = "SuperSecure101" How can I trigger the AngularJS Form validation befo ...

Is there a more effective approach to designing a login screen?

I am just starting out with angular js and this login page is my first step. I have created a basic login form, but when I click on the login() button, the form() does not get submitted and it keeps showing an error message saying "invalid username and pas ...

Creating the jquery/javascript code needed to produce an event or alert similar to the "Confirm Navigation" prompt used on sites like Stack Overflow

Similar Question: How can I have a confirmation message when navigating away from a page after making changes? I've noticed an interesting feature on Stackoverflow: when you start writing a new question and attempt to leave the page, it prompts y ...

Creating a variable by using a conditional operation in JavaScript

When the statement <code>name = name || {} is used, it throws a reference error. However, using var name = name || {} works perfectly fine. Can you explain how variable initialization in JavaScript functions? ...

What is the best approach to achieve the old THREE.SpriteAlignment effect in the latest version of three.js?

After adapting an old three.js code for my application that includes a 3D function with axes grids, I encountered an issue when trying to update it to the latest revision, r74: https://jsfiddle.net/cjfwg2c4/ Without THREE.SpriteAlignment.topLeft, sprites ...

Can you provide some insight into why the init() method is throwing an error?

My project utilizes DynamoDB access through https://www.npmjs.com/package/react-native-dynamodb. I followed the code provided on the website for implementation. The issue I'm facing is that when hovering over my .init() method in WebStorm IDE, it sho ...

A step-by-step guide on accessing an API to check the status updates of ongoing API calls

I'm facing an issue with making two API calls concurrently. The goal is to have call X executed first, while Y should run in parallel and keep calling itself recursively until the X API resolves. Both calls should be initiated immediately upon clickin ...

Changing the text of a link when hovering - with a transition

Seeking a straightforward way to change text on a link upon :Hover. I desire a gentle transition (text emerges from below) and fallback to default if JavaScript is disabled. HTML <div class="bot-text"> <a href="">Visit this site</a> ...

Utilize getJSON to refresh the JavaScript datetimepicker

I am currently using an api with ajax (getJSON) to append data to a specific div called 'open' on my website. However, I now want to update the static values in my datetime picker script for minTime and maxTime. Here is the code snippet: AJAX ...

Lending a hand in deselecting a rule within the jcf-hidden add-on using Selenium

Currently, I am working on automating a website that utilizes the jcf-hidden class (a form of jQuery class) which hides the select element I want to access. By removing the display: block !important; property, I was able to successfully interact with the ...

Chrome has some issues with resizing the SVG Pattern element

Utilizing inline svgs, I have a svg circle filled with a pattern that should cover 100% of the container size. However, when the parent element is resized via JavaScript, the pattern no longer reflects the 100% width and height as expected. This issue seem ...

Correct validation is not achieved when the "!" symbol is used in the matches function

I am working on a React and Next.js project where I am using Formik for handling forms and Yup for validations. One specific input field requires some validations to be performed. This field must be required, so if the user does not enter any information, ...

What could be causing my divs to collide with each other in a Javascript environment?

As you may be aware, my current task involves assigning random positions from a list to various div elements. The code I am using to achieve this is as follows: var list = [100,210,320,430]; var square1 = document.getElementById("square1") var sq ...

The text's worth in the code of javascript

Having an issue with my code where I want to add a string to my Confirm() function in JavaScript but it's not working correctly. myData.setValue(i, 9, '<a href="'+scriptDelete+'" onclick="return confirm();" > Delete </a>&ap ...

React Native - Implementing asynchronous array filtering using async/await

In my code, there is a filtering method implemented as follows: _filterItems(items) { return items.filter(async item => { let isTrue = await AsyncStorage.getItem('key'); return isTrue; }) } However, when calling the method this._ ...

ngResource transformResponse guide on dealing with both successful and erroneous responses

When my API, built using expressJS, returns JSON data as a regular response, everything functions smoothly. However, when an error occurs, it returns an error code along with plain text by simply invoking res.sendStatus(401). This poses a challenge on my ...

The Execution of a Function Fails When Passed to a Functional Component

My functional component accepts a function called addEvent, which expects an event parameter. The problem arises when I try to call this function from props within another functional component, as the function does not seem to execute: const onOk = () =&g ...