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

Unable to sign out user from the server side using Next.js and Supabase

Is there a way to log out a user on the server side using Supabase as the authentication provider? I initially thought that simply calling this function would work: export const getServerSideProps: GetServerSideProps = withPageAuth({ redirectTo: &apos ...

A method for applying the "active" class to the parent element when a child button is clicked, and toggling the "active" class if the button is clicked again

This code is functioning properly with just one small request I have. HTML: <div class="item" ng-repeat="cell in [0,1,2]" data-ng-class="{active:index=='{{$index}}'}"> <button data-ng-click="activate('{{$index}}')">Act ...

Adjust the href link value when a new option is selected

I currently have a select element displayed below. Next to it, there is a link that sets the eID value to a session value. However, I want this value to be updated dynamically whenever a different eID value is selected from the dropdown. Although I can r ...

Issue with FontAwesome icon selection in Vue2 (nuxt) not displaying icons

If you're looking for the icon picker, you can find it here: https://github.com/laistomazz/font-awesome-picker I've tried running it, but unfortunately, the icons are not showing up. When I inspect the elements, the code is there but the icon is ...

[ERROR] There was a problem encountered during the execution of the ionic-app-scripts subprocess

I encountered an error while running my Ionic project. Below is the error message: [ERROR] ionic-app-scripts has unexpectedly closed (exit code 1). The Ionic CLI will exit. Please check any output above for error details. ionic3-firebase-shopping-car ...

Merging HTML Array with jQuery

I am working with input fields of type text in the following code snippet: <input type="text" minlength="1" maxlength="1" class="myinputs" name="myinputs[]" > <input type="text" minlength="1" maxlength="1" class="myinputs" name="myinputs[]" > ...

Modify radio button colors upon selection with a variety of colors

Looking to create Yes/No buttons that start with a default state of null and change color when pressed - green for yes, red for no. Check out this example code: <label class="formheading">Apparatus group is correct</label> <fieldset data-r ...

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 ...

Warning: React has detected that a non-boolean value of `true` was received for the attribute `my-optional-property`

source code import React from "react"; import { Button, ButtonProps } from "@material-ui/core"; interface MyButtonProps extends ButtonProps { "aria-label": string; "my-optional-property"?: boolean; } function MyCustomButton(props: MyButtonProps) { ...

Leveraging ajax data to enhance visual representation in graphs

Having trouble fetching data from a database to display it in a graph.js graph. I've attempted setting a timeout for the async callback from Ajax, but nothing seems to be working. Any suggestions on how to make this work would be greatly appreciated! ...

Identifying keystrokes and triggering audio in Vue.js

Utilizing vue.js, the code snippet provided enables sound playback upon each button click. I am curious about how one can detect a keyboard press event to play a sound when the DOM is ready rather than waiting for button clicks. For instance, triggering ...

Streamline a javascript code with numerous elements

Seeking assistance in simplifying this code Currently, I find myself constantly updating this code each time a new entry is uploaded. I am looking for a solution where there is a single script that can identify the element IDs ("#rolly" or "#lagrimas") a ...

How can you make a Dropdown Box with Javascript?

My current table setup is as follows: <table> <tbody> <tr> <td>List 1</td> <td>List 2</td> <td>List 3</td> <td>....</td> </tr> <tr> <td>This section would be the dropdown ...

Insert elements to an XML document in Node.js using libxmljs

I've been working on updating an XML file by adding a new child node using the code below: var libxml = require('libxmljs'); var xml = '<?xml version="1.0" encoding="UTF-8"?>' + '<root>' + ...

The functionality of OnPress for React Native Google Places Autocomplete is hindered by its surrounding parent components

I'm currently implementing the react-native-google-places-autocomplete library in my React Native application. However, I've encountered an issue when trying to select an address from the suggested list provided by Google. Whenever I click on a s ...

Show a Toast in React without relying on useEffect to manage the state

I have successfully implemented the Toast functionality from react-bootstrap into my application using the provided code. However, I am unsure if it is necessary to utilize useEffect to set show with setShow(items.length > 0);. Would it be simpler to ...

Utilizing Vue and Websockets for seamless communication: Managing the exchange of messages between users

In an attempt to create a messaging system that shows alerts of messages to different users, I have implemented Vue Socket Io from https://www.npmjs.com/package/vue-socket.io. However, the issue lies in the fact that the alerts are not being triggered as e ...

Instructions on how to eliminate the minutes button from Material UI datetime picker

I'm currently working on customizing a datetimepicker from materialUI in ReactJS. My goal is to prevent the user from seeing or selecting minutes in the picker interface. Despite setting the views prop to include only year, month, date, and hours, use ...

Issue with retrieving data from controller in Spring MVC 3 using jQuery and AJAX via $.get method. The value is not being returned to the

I am currently diving into the world of AJAX, particularly in conjunction with Spring MVC. However, I am encountering some challenges along the way. Before delving into my actual real-time project requirements, I decided to test out the AJAX+Spring MVC+jQ ...

What is the best way to iterate through JavaScript objects within a Jade template?

Technologies such as Node.js, Jade, socket.io, jQuery, and JSON are being used in my project. In my "index.jade" file, I have the following code that receives "results" data as JSON from the backend: extends layout block content ul // more jade html h ...