Is it advisable to incorporate await within Promise.all?

Currently, I am developing express middleware to conduct two asynchronous calls to the database in order to verify whether a username or email is already being used. The functions return promises without a catch block as I aim to keep the database logic separate from the request/response/next logic. Additionally, I have centralized error handling that requires 'next' as an argument. During testing with Postman in my local environment, the code below behaves as expected and the centralized error handler effectively returns any errors to the client:

async checkUsernameExists(username) {
    await this.sequelize.transaction(
      async () =>
        await this.User.findOne({
          where: {
            username,
          },
        }).then(user => {
          if (user) throw new Conflict('Failed. Username already in use.');
        }),
    );
  }  

const checkDuplicateUsernameOrEmail = async (
  { body: { email, username } },
  res,
  next,
) => {

  await Promise.all([
    checkUsernameExists(username),
    checkEmailExists(email),
  ])
    .then(() => next())
    .catch(error => next(error));
};

However, since the 'checkExists' functions are asynchronous, should they not be included in 'Promise.all' with the 'await' keyword? Or does 'Promise.all' handle this behavior automatically?

await Promise.all([
    await checkUsernameExists(username),
    await checkEmailExists(email),
  ])...

This results in an unhandled promise rejection from 'checkUsernameExists' and no response being sent back to the client.

Answer №1

Is it okay to use await within Promise.all?

No, it is not recommended (at least not in the way it is currently being done). Promise.all is designed to handle an array of Promises. When all Promises in the array have resolved, or if one rejects, the overall Promise.all will resolve or reject accordingly. If you include await within the array, you are essentially passing non-Promise values to Promise.all, which goes against its intended functionality. Additionally, using await in this context means that the Promises will be resolved sequentially, rather than simultaneously as intended by Promise.all.

await Promise.all([
    await checkUsernameExists(username),
    await checkEmailExists(email),
  ])...

For instance, if checkUsernameExists takes 0.5 seconds to resolve and checkEmailExists also takes 0.5 seconds, using the current approach would result in a minimum of 1 second for the entire Promise.all operation to complete. This delay occurs because each Promise is resolved with an await call instead of letting Promise.all manage their simultaneous resolution.

The correct approach should be:

await Promise.all([
  checkUsernameExists(username),
  checkEmailExists(email),
])

Remember, async functions inherently return Promises. Therefore, passing the function directly into Promise.all will work as expected without needing additional await calls within the array.

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

Why does the return value of a function in Node.js and JavaScript sometimes appear as undefined?

I am completely stumped by this issue. I've been trying to figure it out, but so far, no luck.. this is the code snippet function part1(sql, controltime, headers_view, results_view, tmp){ var timerName = "QueryTime"; var request = ne ...

Undefined values in Javascript arrays

Currently, I am sending a JSON object back to a JavaScript array. The data in the array is correct (I verified this using Firebug's console.debug() feature), but when I try to access the data within the array, it shows as undefined. Below is the func ...

Set options for nested arrays with up to n levels of children

My project involves building a category module using Laravel for the backend and Vue.js for the frontend. I have incorporated the library Laravel Nestable The library has been successful in producing the desired output. [ { "id": 1, "name": "C ...

Unable to Restart or Begin a Paused Process within PM2

Running PM2 on my server to manage Node.Js processes has been smooth sailing for the most part. However, there is a hiccup I encounter when trying to temporarily stop a service for various reasons. Oddly enough, I face an issue where I cannot start a proc ...

Establish validation parameters for uploading multiple files

I need to implement client-side validation for my FileUpload control to ensure that users can only select up to 10 images. While I already have the server-side code in place, I now want to add client-side validation as well. Sample Code: <asp:FileUplo ...

Creating personalized tags or components by utilizing insertAdjacentHTML in Vue

With the use of insertAdjacentHTML, I am able to create HTML elements such as div and span, but it seems that I cannot generate custom tags like <myComponent> </myComponent>. I understand that insertAdjacentHTML can create HTML elements, but a ...

I am encountering an issue with the return ( statement and I'm unable to comprehend the reason behind it

import { connect } from 'react-redux' import { Link } from 'react-router-dom' class MyFavoriteStories extends React.Component { markAsFavorite = (e) => { this.setState({ bgColor: "blue" }) } render () { con ...

Executing commands following a JSON loop in jQuery

I'm experiencing an issue with jQuery. When my page loads, I fetch a JSON file and loop through its items. However, I am unable to attach any event listeners to the input button that is added. For instance, I want to display an alert message... It s ...

Encountering an error "[$rootScope:inprog]" while using Angular select with ngModel

I'm still learning my way around Angular, but I have a basic understanding. Right now, I'm working on assigning access points to a building using a <select> element. I've created a simple controller for this task, but it's not fun ...

The array functions properly when handwritten, but fails to work when loaded from a text file

I have been developing a password recommendation script that aims to notify users when they are using a commonly used password. In order to achieve this, I decided to load the list of common passwords from an external text file. However, it seems that the ...

What is the process for changing a DynamoDB table from PROVISIONED to PAY_PER_REQUEST using Node.js?

Currently, I have a DDB table set up with BillingMode: PROVISIONED and ProvisionedThroughput:{...}. My goal is to switch it to BillingMode: PAY_PER_REQUEST, but every time I attempt this change, I encounter the following error: TypeError: Cannot read prop ...

What could be causing the React text input to constantly lose focus with every keystroke?

In my React project using Material-UI library, I have a component called GuestSignup with various input fields. const GuestSignup = (props: GuestSignupProps) => { // Component code goes here } The component receives input props defined by an ...

Activate the HTML drop-down option upon selecting the radio button, or the other way around

I'm attempting to accomplish a task. Below is the code snippet I am working with: <form> <input type='radio' name='radio_flavour' checked/>Unique flavour<br/><input class='double-flavoured' type=&apo ...

Securing Confidential Information in Vue Data Storage

For the last month, I've dedicated my time to learning Vue. However, there's still one question that puzzles me: The web application I'm currently developing allows users to maintain daily diaries for different projects. They should be able ...

Encountering an empty array as the aggregate output after utilizing the $unwind operator

I have a document that looks like the one below, and I've applied an aggregate query using mongoose. However, when I run the query on the json data displayed below, it returns an empty array. I believe there might be a mistake in my query related to t ...

Can you explain the distinction between server-side rendering in Next.js and static site rendering in Gatsby.js?

I'm interested in developing a website without depending on client-side JavaScript, but I still want to incorporate SPA features such as client-side routing. To achieve this, I am considering using a framework that does not rely on rendering on the cl ...

Is it possible to reference a .js file within an HTML file using AngularJS?

Having a slight issue with an email function. I experimented with the 'nodemailer' package and successfully sent an email when coding in a .js file. Upon calling the .js file (node emailfile.js), the email was received as expected (code provided ...

I'm encountering an operation timeout error in my sequelize connection. Any suggestions on how to resolve this issue?

Using Sequelize ORM in my NODE JS and PostgreSQL setup has been great, but recently I encountered an issue. When multiple requests are made to the server concurrently, an error is thrown: ConnectionAcquireTimeoutError [SequelizeConnectionAcquireTimeoutErro ...

Sticky header in React data grid

Is there a way to implement a sticky header for a data grid in react? I have tried various methods but haven't been able to figure it out. Any suggestions would be appreciated. You can find my code sandbox example here. #react code export const Styl ...

The issue of the menu in the <Select /> component unexpectedly closing is caused by the MaterialUI -withStyles higher-order component (HOC)

Issue Description When utilizing the <Select /> component with the multiple attribute, users should be able to select multiple options without the dropdown menu closing. This functionality works as intended when using the <Select /> component ...