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

Creating Browser Extensions with Vue.js and Vue CLI

I am in the process of creating a Chrome Extension with a frontend powered by Vue.js. Everything was going smoothly using vuecli until my app started utilizing the Webextension-API. This API is only accessible to registered Extensions, not normal websites. ...

Tips on locating information within a pre-existing GET array with parameters provided

Apologies for the unclear title. I am currently utilizing a category chooser that pulls categories from an API. The process involves fetching a list of categories, filtering out their names, and presenting them in the category chooser. Upon clicking submit ...

utilizing array.map() to nest multiple layers of arrays

I am facing a challenge with a JavaScript array structure that contains three top-level objects. Each of these objects has an "teamLineup" array, which in turn holds two more objects named "team". These "team" objects have another array called "starters", ...

Unusual Behavior of JavaScript for..in and enum

I'm facing an issue with the peculiar behavior of the for..in loop in JavaScript. Here's the structure of my HTML: <div id="quarter_circle_top_left">...</div> <div id="quarter_circle_top_right">...</div> <div id="quart ...

Issue arises when the project directory lacks the pre-existing node_modules while docker-compose and volumes are being utilized

I've encountered an issue where I need to create the node modules folder before running Docker, otherwise I get a "vite not found" error. docker-compose.yml: version: "3.4" services: node: build: context: .. dockerfile: . ...

Why would npm be unable to locate a file, potentially leading to an error? Could the lack of contents in my node_modules subfolder be the root cause of this issue?

I'm encountering an issue while attempting to execute npm install in the angular project directory obtained from ASP.NET Boilerplate. The error I'm facing is related to npm's inability to locate a specific file. D:\Dev\AspNetBoiler ...

Construct a div element using JSON information

I am retrieving information from a database and organizing it into a JSON array. Here is the data that I have: [{"id":"0","name":"red","percentage":"60"},{"id":"1","name":"blue","percentage":"58"},{"id":"4","name":"green","percentage":"12"}] The structu ...

The Uglify task in Grunt/NPM is having trouble with this particular line of JavaScript code

Whenever I execute grunt build, Uglify encounters a problem at this point: yz = d3.range(n).map(function() { return k.map(x -> x[1]); }), An error message is displayed: Warning: Uglification failed. Unexpected token: operator (->). I have recentl ...

Removing an element from an array within MongoDB

After closely examining my mongodb data structure, it appears like this: [ { "_id": "582bc918e3ff1bf021ae8b66", "boardName": "Test Board", "created_at": 1479264483957, "__v": 0, "person": [ { "name": "Steve", "w ...

Consistently failing to retrieve the anticipated data from the file

I have utilized node.js to create a custom 'search(string)' function that makes an API request, retrieves the response payload object, and then saves it to a file. When running tests in my test file by calling this function with different parame ...

Discovering whether an ID exists within a variable containing HTML code

I am currently attempting to determine if the ID is included in a variable containing HTML content. The ID name is being added to a DIV element through dynamic variables. strHTML = "<div id='"+var1+var2+"'>" Now, I want to verify if a sp ...

I am encountering an issue where my react file appears to be completely overlooked when I try to access it through my web browser. Can anyone provide guidance on how

import React, { useState } from 'react'; function NumberInputForm() { console.log('NumberInputForm component rendering...'); const [number, setNumber] = useState(''); const handleInputChange = (event) => { const ...

What is the best way to minify and concatenate multiple CSS files only after converting SCSS to CSS with Gulp?

When attempting to convert my scss files to css files using gulp, I encountered an issue. After writing the scss code, it is easily converted to css. However, I wanted to minify this css and save it in a different folder called 'min'. Within the ...

What is the best way to simulate a constructor-created class instance in jest?

Suppose there is a class called Person which creates an instance of another class named Logger. How can we ensure that the method of Logger is being called when an instance of Person is created, as shown in the example below? // Logger.ts export default cl ...

After upgrading from Vuetify version 1.5 to 2.0.18, an issue arises with modules not being found

I encountered the following error: module not found error To address this issue, I took the following steps: Commented out import 'vuetify/src/stylus/main.styl' in the src/plugins/vuetify.js file. Added import 'vuetify/src/styles/main. ...

Adhering button for sliding side panel

Check out my JSFiddle HERE to see what I have done. I would really appreciate it if someone could help me figure out how to make the show button float with the sidr panel :) <style type="text/css"> #panel { position: fixed; top: 50%; r ...

What sets apart getStaticProps + fallback:true from getServerSideProps?

I have gone through the Next.js documentation multiple times, but I am still struggling to grasp the difference between using getStaticProps with fallback:true and getServerSideProps. From my understanding: getStaticProps getStaticProps is rendered at b ...

Issues arising from using async/await in conjunction with .then() in vue.js login function, causing fetch process not to wait for completion

I implemented a login function to verify credentials on my backend server, but I am facing an issue with waiting for the server response. Despite following the es7-async-await.js guide and trying various async/await and promise techniques, the function sti ...

I am attempting to add a new row (div) for the invoice, but when I do so, the

Looking for a solution to repeat a row when clicking a button in order to utilize PHP for data manipulation? Check out the code snippet below: <!-- Table row --> <br><br> <div class="row"> <!--Product Table--> <div ...

I keep getting double results from the Multiple Checkbox Filter

Currently, I am facing an issue with a checkbox filter on a product page that I'm developing. The filter is functioning correctly, but I encounter duplicate results when an item matches multiple criteria. For instance, if I select both 'Size 1&ap ...