How can I correctly format a conditional statement within flatMap while using Promise.all in Javascript?

Currently, I am developing a scenario where I use flatMap alongside Promise.all. Within the flatMap function, there are two specific conditions to consider: firstly, checking if the state of the originalObj is false or not before proceeding with the insertRealStartTime, and secondly, regardless of this condition, implementing the Event.updateMany for each event. Additionally, I need to ensure that the return value of Events.updateMany() indicates the success of the update operation.

function async foo(){
  const eventPromises = events.flatMap(async (event) => {
      if (event.state.matchPhase == "1H") {
        // simpleQuery is async function
        const originalObj = await simpleQuery({ id: event.id });
        if (originalObj.state == false) {
          // insertRealStartTime is async function
          await insertRealStartTime(event.id);
        }
      }
      // Event.updateMany is async function
      await Events.updateMany(
        { ...event, expireAt: event["startTime"] },
      );
    }
  );
  const all = await Promise.all(eventPromises);
  console.log(all)
}

Upon executing the code, I noticed that the output in console.log(all) displays an array of undefined. It appears that the misuse of await within flatMap might be causing this issue, as it interferes with the purpose of using Promise.all. How can I properly handle these conditional statements in order to execute the asynchronous functions based on the conditions while utilizing Promise.all effectively?

Answer №1

The flatMap callback you're using does not include a return statement, causing the promises from the async calls to resolve as undefined.

To obtain the values resolved by the updateMany() promises, they should be explicitly returned.

You have a couple of options to achieve this:

  1. Get the result of await Events.updateMany() and return it:

    const success = await Events.updateMany();
    return success;
    
  2. Simply return the promise generated by Events.updateMany():

    return Events.updateMany();
    

Both approaches will work effectively.

While not problematic, in cases where the callback returns a promise (like yours), utilizing flatMap is unnecessary. Instead, use map, as async callbacks always produce promise objects and not arrays as return values.

If you make some adjustments to your code, it could look like this:

function async foo() {
  const eventPromises = events.map(async (event) => {
      if (event.state.matchPhase == "1H") {
        // You can destructure here to only extract the state property
        const {state} = await simpleQuery({ id: event.id });
        if (!state) { // Utilize the NOT operator
          await insertRealStartTime(event.id);
        }
      }
      // Ensure to return the promise
      return Events.updateMany(
        { ...event, expireAt: event.startTime }
      );
    }
  );
  const all = await Promise.all(eventPromises);
  console.log(all);
  return all; // Give something meaningful back to the caller...
}

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

Alternatives to AMP in AngularJS

My current project is based on Angular 1.x and I recently received advice from an SEO specialist to enhance the initial mobile load speed of my website. One suggestion was to implement AMP, but after some research, it appears that integrating AMP with Angu ...

The SVG format quickly displays new and larger datasets on line charts without any transition effects

My goal is to create a line chart with animated transitions similar to this demo, but without the dots. I am attempting to integrate this functionality into a react component where the update method can be triggered by another component, allowing the d3 op ...

What could be causing the appearance of a mysterious grey box hovering in the upper left portion of my image and why is the code only adjusting the size of the grey box instead of the entire

I've been working on embedding some JavaScript into my Showit website to create a drag-and-drop feature that displays a collage/mood board effect. Everything is functioning correctly, but I'm running into issues with resizing the images. There&a ...

Utilizing Angular 2 for Integration of Google Calendar API

I recently attempted to integrate the Google Calendar API with Angular 2 in order to display upcoming events on a web application I am developing. Following the Google Calendar JavaScript quick-start tutorial, I successfully managed to set up the API, inse ...

The Express application fails to receive a response from a Mongodb query function

In my current project, I am implementing a simple API Key authentication system. The main goal is to validate the provided key against the user's input. There is a separate file containing a function that queries the database and returns either true/ ...

What is the reason behind arr.reverse() flipping the original array?

My goal is to reverse an array and store the reversed version in a new array without altering the original array. Here is the code I am using: var arr= ["1", "2", "5"] var arrTwo = arr.reverse(); console.log(arrTwo) \\ ["5" , "2" , "1"] console. ...

Welcome to the launch of OpenWeatherMap!

I just signed up for an account on the OpenWeatherMap website. My goal is to retrieve the current weather information for a specific location using the City ID API Call: http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myAPIKey How ca ...

Issues encountered while trying to implement HTML text within span tags

In my code snippet, I am using a span element: <span> {textToRender} </span> The purpose of this code is to render HTML text (as a string) within a span element. some text <br/> some text <br/> some text <ol>text However, wh ...

Error: React.js - operationStore.getItems function is not defined

I've encountered an issue while running my Web App with the command: node --harmony gulpfile.babel The error message states: Uncaught TypeError: operationStore.getItems is not a function I'm struggling to identify the root cause of this problem ...

Exploring React: Opening a new page without rendering the SideBar component

I currently have an application with a sidebar that navigates to three different pages, all of which include a navigation bar and the sidebar. However, for the next page I want to exclude the sidebar but still include the navigation bar. How can I configur ...

My mocks for Jest's readFile and writeFile functions are not being loaded

Just wondering, when using jest.mock(), can I only mock the entire module or can I also mock exported functions and constants? In my app.js file, I am using const fileSystem = require('fs'). I am trying to test an method in the app that reads a f ...

What could be causing the incorrect output when an else statement is included?

When I run the code provided below, I am getting a different answer depending on whether the else statement is included or not. Without the else statement, the answer is true, but with the else statement it is false. Can anyone explain why this is happen ...

The MUI persistent drawer navigation bar becomes dysfunctional when accessing a specific route

Exploring the MUI library for the first time, I successfully created a navigation bar that functions properly for one route (Dashboard). However, when attempting to implement it on the candidate route, it collapses as shown in this Screengrab of collapsed ...

When using JavaScript to dynamically load canvases and create drawing contexts within a function, the context may suddenly disappear

Currently, I am modifying the canvases displayed through ajax calls and also updating what is drawn on each canvas. The primary issue I am facing is that my main drawing function fails on getContext and there are some unusual behaviors such as missing canv ...

Instead of adding a new object to the array, consider increasing the quantity of an existing object

I am new to working with a shopping cart component and my code is structured like this: let cartCount = document.getElementById("counter"); let isItemSelected = false; let itemCount = 0; let shoppingCart = []; let selectedSize = ""; let displaySelectedSiz ...

Adjusting diagram size based on screen width using Bootstrap and jQuery

I recently created a diagram that adjusts its size according to the screen width. However, when I implemented this code on my page, I encountered an issue where the final circle or glyph would drop to the next line instead of staying on the same line as in ...

Consolidate multiple generic items into a single entry

In my current project, I am structuring the types for a complex javascript module. One of the requirements is to handle multiple types using generics, as shown in the snippet below: export interface ModelState< FetchListPayload, FetchListR ...

Error in Google reCaptcha 2: "a is null" occurs when grecaptcha.reset function is executed

I am currently working on a registration page that utilizes AJAX for validation on both the client and server sides. If the server side validation fails, the AJAX function returns the errors to the screen and tries to reset the reCAPTCHA using grecaptcha. ...

Using the Twit package on the client side: a step-by-step guide

I have been utilizing the Twit package for searching tweets. After executing the js file in the console, I am able to see the tweets but when trying to use them on my webpage, an error 'Uncaught ReferenceError: require is not defined' pops up. Th ...

Can you explain the significance of "mongodb is not a function"?

As a novice in the world of programming, I am currently diving into a web development course. However, I encountered an error while trying to connect to a database I created. The error message states that "mongodb.connect is not a function." Below is the ...