Do parallel awaits in JS/TS work only on Chrome browsers exclusively?

Encountering a strange issue with promise resolution behavior in JS/TS. Using Node LTS. It seems that the difference lies in whether the promise resolves to a value that is later read in the code or if it's simply fire-and-forget (void response type). Would appreciate insights from experts.

A recent Google dev blog suggests that delaying your await call on two async/await functions can cut wait time in half.

Original post: https://web.dev/async-functions/#careful-avoid-going-too-sequential

However, this logic does not seem to apply on node.js (both v16 and v18/lts).

If we wrap their example in an async IIFE, we can test it using the following code:

(async () => {
  function wait(ms, value) {
    return new Promise(resolve => setTimeout(resolve, ms, value));
  }

  const t = 500
  const msg = 'done'
  const wait1 = wait(t, msg); // Start a 500ms timer asynchronously…
  const wait2 = wait(t, msg); // …which means this timer runs in parallel.
  await wait1; // Wait 500ms for the first timer…
  await wait2; // …by which time the second timer has already finished.
  console.log(wait1, wait2)
})()

Observe the values of wait1 and wait2 in the concluding console.log statement.

console.log(wait1,wait2)
// Promise { 'done' } Promise { 'done' }

Why do wait1 and wait2 still remain unresolved promises even after awaiting them?

This additional observation raises further doubts about the logic flow here. When we await those variables again in console.log, the promises are finally resolved...

console.log(await wait1, await wait2)
// done done

So, by awaiting these variables again, we eventually get resolved promise values?

Is this discrepancy between Node and Chrome's V8 implementation intentional, or is it related to how we handle resolved promise values versus just awaiting a function with a void response?

Answer №1

Is there a reason why the promises wait1 and wait2 are still unresolved even after using await on them?

Even when a promise is fulfilled with a result, it still remains as a promise object. There is no special transformation happening, and the variables continue to hold the promises themselves rather than the results. When you use an await expression, it does provide the result value, but simply calling await on wait1 or wait2 just disregards that result.

To handle this situation correctly, you should do the following:

const wait1 = wait(500, 'done1');
const wait2 = wait(400, 'done2');
const res1 = await wait1;
const res2 = await wait2;
console.log(res1, res2); // instead of console.log(wait1, wait2)
//          ^^^^  ^^^^

Alternatively, a much better approach would be (as mentioned in this stackoverflow post and this one):

const [res1, res2] = await Promise.all([wait1, wait2]);
console.log(res1, res2);

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

What does "t=" represent in the socketIO URL?

I am just starting to learn about socketIO, and I have noticed that every time I connect to a node server through socketIO, it creates a URI that looks like https://XXX:8080/socketIO/1/?t=XXXXXXXXXXX Could someone explain what the "?t=XXXXX" part is for ...

When attempting to pass react-intl as an argument in a method of a React component during Jest testing, an error is thrown stating, "TypeError: intl.formatMessage is not a function."

Currently, I am in the process of unit testing my React component using Jest. Within this component, there are several methods that are called upon. As an example: export function fetchText(text, intl) => ((text !== 'NA') ? (intl.formatM ...

Is my input file in Javascript valid and does it exist? Here's how to check

In my Javascript code, I am retrieving strings from a text file. When the user inputs an incorrect or invalid file name, I want to display a message. For example: console.log("Your input is invalid"); Here is the code snippet that reads the text file and ...

Incomplete Loading of Google Maps

Let me clarify that the solutions I have come across so far have not been successful. I am attempting to display a modal alert with a basic Google Maps integration. Problem: Google Maps does not load completely. Snippet from my .js file: var map; functi ...

A step-by-step guide on integrating a basic React NPM component into your application

I've been attempting to incorporate a basic React component into my application (specifically, React-rating). After adding it to my packages.json and installing all the necessary dependencies, I followed the standard instructions for using the compon ...

Is there a way to refine a table based on the specific rows that are chosen in ag-Grid?

Is it possible to filter a table by rows with the attribute select: true, considering that select is not part of the data but rather an attribute of RowNode? I have tried using gridApi.getSelectedNodes() as well as text and number filters, but haven' ...

contrasting the application of logic in Rails controllers versus JavaScript within the .js.erb files

When dealing with a large "data" active record object that needs to be filtered based on user interactions on a page, the question arises about where to place the data-filtering logic. Currently, the filtering is done in the rails controller action, simpli ...

Choosing a default selected value from a dropdown list with multiple editing options

When loading my "multiple edit" screen, I default the values as follows: private createFormGroupItem(item: ...): FormGroup { return this.formBuilder.group({ title: new FormControl(item.title, [Validators.required]), effectiveDate: new FormC ...

Bring in React components using a specific namespace

Here is the structure of my React component: /build .............................. /lib /inner /InnerComponent.js /index.js /OuterComponent1.js /OuterComponent2.js /index.js ................................. package.jso ...

The one-time binding notation does not seem to be functioning as expected in AngularJS version 1.6.4

For our application, we are utilizing AngularJS 1.6.4 to display a large number of rows on a single page. However, when it reaches around 7K entries, the page starts hanging. To tackle this issue, we have opted for one-time binding for those specific pages ...

Using v-for to pass two properties to a single component in VueJS

Hey there! I'm trying to create a v-for loop with a component that has two different props COMPONENT <template> <div class="bg-light rounded p-2 px-5"> <h5> {{ number }}</h5> <h3>{{ item }} ...

The TypeScript error code TS2339 is indicating that the 'modal' property is not recognized on the type 'JQuery'

I'm currently utilizing Typescript with AngularJS and have encountered an issue with modals when using the typed definition of jQuery library. The specific error message I am receiving is: 'error TS2339: Property 'modal' does not exist ...

What are the steps for making Ajax calls?

I have been working on a Wikipedia viewer for my freecodecamp project. However, I am facing issues with the AJAX request as it keeps failing every time without returning any results. var url, value; $(document).ready(function() { $("button").on("click ...

Code for remotely connecting to a server and starting a Node.js application called app.js via SSH

I am attempting to establish an SSH connection to two servers sequentially in order to execute the following command: sudo node app.js This is the code I am using: #!/bin/bash while read line; do ssh -i "sshtest.pem" ec2-user@$line "sudo node app. ...

Can a web application determine if Microsoft Excel has been installed?

Currently, I am developing a web application using ASP.NET that includes certain functionalities which rely on Microsoft Excel being installed on the user's device. In case Excel is not available, I would prefer to deactivate these features. I am foc ...

Ways to send data to a popup in svelte

Hey there, I could really use some assistance with my Svelte app. I'm trying to implement a modal and pass a parameter to the modal component in order to customize its content. However, when using the open() function of Modal, we only need to provide ...

Develop a user interface designed specifically for a subset of JSX.Elements or ReactElement

For better organization, I decided to create an interface called IconInterface to group all my icons: import { IconProps, CaretProps, CheckboxProps } from "./IconProps"; interface IconInterface { (props: IconProps | CaretProps | CheckboxProp ...

Best practices for effectively managing interface design

My current interface looks like this: export interface Folder { name: string; id: number; date: Date; } However, in the actual scenario, the JSON response provides the date as a string type. How should I handle this data transfer between the back-en ...

Can a Typescript class type be defined without explicitly creating a JavaScript class?

I am exploring the idea of creating a specific class type for classes that possess certain properties. For example: class Cat { name = 'cat'; } class Dog { name = 'dog'; } type Animal = ???; function foo(AnimalClass: Animal) { ...

Enhancing Angular input validators with updates

Working on a project with Angular 6, I have set up an input field using mat-input from the Angular Material framework and assigned it an id for FormGroup validation. However, when I initialize my TypeScript class and update the input value, the validator d ...