Iterating through an array and setting variables according to asynchronous code

I have created a function to loop through an array, call a promise, and update a variable based on the result. The code seems to be functioning correctly, but I am wondering if there is a more optimal way to write it. Any suggestions are appreciated. Thank you!

/**
*
* u/returns Resolves a promise and returns value 'b'
*/
async function generatePromise() {
   return Promise.resolve('b');
}

async function main() {
   let showWarning = false;
   // List of users
   const users = ['a', 'b', 'c'];
   //Looping through users array and compare the result from promise and update showWarning boolean
   await users.reduce(async (promise, user) => {
     await promise;
     const result = await generatePromise();
     if (result === user) showWarning = true;
   }, Promise.resolve())

   console.log(showWarning)
}
main();

Answer №1

It appears needlessly complex and the reasoning is somewhat convoluted. Assuming that generatePromise consistently returns the same result, why would you invoke it multiple times? Simply call it once and verify if the result is present in the array:

const showWarning = users.includes(await generatePromise());

If the function must be invoked multiple times (for instance, because it might produce different outputs for each input/user), a straightforward solution can be to utilize a basic for loop:

for (const user of users) {
  if (user === await generatePromise()) {
    showWarning = true;
    break; // why continue checking other users if `showWarning` will not change anymore?
  }
}

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

Linking query branches without encountering the "Exceeded the number of hooks rendered during the previous render" error

This apollo client utilizes a rest link to interact with 2 APIs. The first API returns the value and ID of a record, while the second API provides additional information about the same record. I combine this information to render the content without using ...

Eliminate repeated elements within a JSON dataset to create a consolidated array

Looking to extract unique data from the JSON object below in order to create a result json with a list of questions and their corresponding choices. Any assistance would be greatly appreciated. Thanks in advance..!! var data = [ { "category": "s ...

Leverage Axios in React to dynamically fetch and display real-time data

Executing an Axios get request in order to retrieve data and display it using React. export function Wareh() { const [wareh, setWareh] = useState([{}]); useEffect(() => { axios.get("http://localhost:1515/wareh").then((response) => ...

The navigation bar in React Router is interfering with the loading of other components

Currently, I am in the process of setting up a simple navigation bar that consists of basic buttons without any complex functionality. However, I have encountered an issue where placing the navbar inside the switch prevents other components from loading ...

Utilizing getters and setters with v-model in a class-based component: A step-by-step guide

Transitioning from an angular background to vuejs has been challenging for me as a newbie. I've encountered issues while trying to bind setter/getter in v-model for an input field. Interestingly, when I directly bind it to a variable, everything works ...

Instead of using a checkmark, consider using step numbers with Mui Stepper's Completed StepIcon

I'm currently utilizing Mui Stepper from [email protected] within a React project. Despite my efforts to search on platforms like Stackoverflow and Github, I have been unable to find a solution for displaying the step number upon completion inst ...

Incorporate JSON data to display SVG images

As a beginner in web development, I have been honing my skills with the AngularJS framework due to its user-friendly nature. Currently, I'm working on pulling JSON data from an API using $http.get method. One of the fields contains an image source i ...

Images showing Strava heat maps retrieved through API

Check out this amazing heatmap created by Strava! I'm curious about how they were able to achieve this - it seems like they are using the API to request overlay images based on the network tab. I have my own geo data, but I'm wondering how I can ...

The outerHeight of Elements measured in pixels

Is there a way to increase the outerHeight() function by adding extra pixels? Let's say we have a variable storing the outerHeight of .pg-sect: var $section = $('.pg-sect').outerHeight(); Now, if I want to add an additional 70px to the he ...

Is it possible to use Immutable named parameters with defaults in Typescript during compilation?

Here is an example that highlights the question, but unfortunately it does not function as intended: function test({ name = 'Bob', age = 18 }: { readonly name?: string, readonly age?: number }) { // this should result in an error (but doesn&apo ...

Searching in real-time with ajax in CodeIgniter framework is a seamless and efficient process

I'm a beginner in CodeIgniter and eager to learn. Currently, I'm facing an issue where the data is not being populated on the search page. In the model: function fetch_data($query) { $this->db->select('*'); $this-> ...

Trying to understand the strange behavior of HTML parsing with jQuery in Javascript and Firefox

I have been working on a script to parse an HTML page using jQuery. The script runs smoothly in Chrome, IE, and Safari, but I'm facing some unexpected behavior while testing it in Firefox (version 36.0.1). Here's the code snippet: $.ajax({ u ...

Manipulate database variables using Javascript

As a beginner in JavaScript, I am seeking assistance with some tasks. I have to save a simple number as a JavaScript variable into a database and display the current value on two websites (with PHP used to retrieve it on the second site). This is my curre ...

The Angular carousel fails to display or operate properly

I am encountering an issue where the content is not displaying when using the angular-carousel directives: <ul rn-carousel rn-carousel-controls rn-carousel-index="carouselIndex" rn-carousel-buffered > <li ng-repeat="slide in slides track by ...

The wonders of jQuery popup windows

A code was discovered that displays a popup, but it currently relies on transparency (opacity: 0). I would like to modify it to use display: none instead, as the transparent window in the center of my website is causing issues. Here is the JavaScript code ...

Add an input element to a form fieldset by employing vue

In my form, I have a staged approach with 3 fieldsets that only appear when the "Next" button is clicked. Now, in the third fieldset, I need to add input elements based on keys extracted from an external json object. Data: data: () => ({ c ...

Disable a button during an AJAX request

Whenever a button is clicked, the record is saved to the database without refreshing the page using AJAX. I have implemented the AJAX code successfully. Now I need guidance on how to manage the state of the Submit button - enabling/disabling it dynamicall ...

Encountering a 404 error when attempting to access static files within a directory using Express Js

Organizing my static files has been a breeze with multiple directories. I have some static files in the client directory, while dashboard-related files are nested within the src directory. Here is how my directory structure looks: / | client //housing sta ...

Exclude a specific link from a JQuery function

Check out this unique single page site that utilizes a waypoint script for navigation and highlighting nav items - The functionality works seamlessly, however, we are facing an issue where we need to modify a link to redirect to an external website. Unfor ...

Having trouble with string matching in JavaScript?

My attempts to verify my Ajax response with a string have consistently resulted in a fail case being printed. Below is the section of code relating to my ajax request: var username = document.getElementById("name").value; var password = document.getEle ...