Is there a way to selectively add elements to the Promise.all() array based on certain conditions?

Here is the code snippet that I have written:
I am aware that using the 'await' keyword inside a for-loop is not recommended.

const booksNotBackedUp: number[] = [];
for (let i = 0; i < usersBooks.length; i += 1) {
        const files = await Util.file.getFiles(Util.file.DATA_BUCKET, { prefix: `${userId}/data/${usersBooks[i]}/sqlite` });
        if (files.length === 0) booksNotBackedUp.push(usersBooks[i]);
    }
console.log('booksNotBackedUp', booksNotBackedUp);

I attempted to refactor the code in the following way, however the 'result' variable ended up containing all elements from 'userBooks', which was not my desired outcome.

const booksNotBackedUp: any[] = [];
userBooks.forEach((book) => {
    booksNotBackedUp.push(Util.file.getFiles(Util.file.DATA_BUCKET, { prefix: `${userId}/data/${book}/sqlite` })
})
const result = await Promise.all(booksNotBackedUp);
console.log('booksNotBackedUp', result);

Please provide some guidance to help out this struggling newcomer😥

Answer â„–1

The condition for adding the promise to an array must be evaluated after the promise has been resolved, as it is not possible to add a promise to an array before that point.

Once all promises have been resolved using promise.all(), you can then perform filtering on the results using the array's filter method.

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

Can a Set (or Map) be held in a "frozen" state?

Despite the fact that Set is an Object, Object.freeze() specifically operates on the properties of the object, a feature not utilized by Map and Set: for example let m = new Map(); Object.freeze(m); m.set('key', 55); m.get('key'); // == ...

Unable to Transmit Authorization Header in Cross-Domain Access Situation

My Node.js server has cross-origin communication enabled, allowing my Vue application to access its API from a different origin where static assets are served. This is achieved by setting the following code in Node.js: res.setHeader('Access-Control-Al ...

Ways to restrict the quantity of Firebase compound indexes required for querying with various filters

I'm in the process of developing a Firestore project that includes group chats and forums where users can filter posts based on various criteria: Number of likes Presence of attachments (photos and/or files) 4 Tags (Questions, Exams, Assignments, Not ...

Idea fails to detect imports

I have been attempting to use Angular2 in IntelliJ IDEA IDE. Although my code is valid (I have tried compiling and executing it), the IDE keeps showing me this error: https://i.stack.imgur.com/w6wIj.jpg Is there a way to configure IntelliJ IDEA to hide t ...

jQuery click event not working post Ajax request returned a 403 error

I am facing an issue with my ajax request where I receive a 403 error message. Strangely, when this error occurs, the click() function associated with the ajax call stops working. There is no manipulation of HTML elements before or after the ajax call, and ...

Tips for Preventing Unnecessary Ajax Requests

What I require When a click event is triggered, a service call should be made only once. Use case Dropdown1 Dropdown2 Dropdown3 1. There are three dropdowns on the HTML page. 2. When Dropdown1 is called - an AJAX call is made only onc ...

Set the Vue 3 Select-Option to automatically select the first option as the default choice

I am attempting to set the first select option as the default, so it shows up immediately when the page loads. I initially thought I could use something simple like index === 0 with v-bind:selected since it is a boolean attribute to select the first option ...

Can you define the type of binding value in AngularJS 1.5(6) using TypeScript?

I am looking to define the type of binding items so that I am able to utilize components similar to functions. For instance, consider a component: angular.module('app').component('navBar', new NavBar()); class NavBar{ public bin ...

What is the proper method for utilizing colspan within the footerData of a jqGrid?

Are you looking to customize the footer of your jqgrid as shown in the example below? I am trying to set up a custom footer for my jqgrid similar to the one displayed above. I have already enabled the footerrow:true option and used $self.jqGrid("footerDat ...

mobx: invoking a class method upon data alteration

Is it possible to utilize the Mobx library in order to trigger a class method whenever data changes? For instance, when MyObject assigns a value of 10 to container['item'], can we have the myaction method invoked? class MyElement extends Compone ...

Steps for mandating the specification of a type parameter for a generic React component

When setting up a new instance of a generic React component, I noticed that the TypeScript type checker automatically defaults to unknown without requiring me to specify the type argument: Ideally, I would prefer if TypeScript prompted for the explicit ty ...

Error in jQuery submenu positioning issue

I am attempting to design a menu that opens when the parent element is clicked and closes when the mouse leaves the previously opened one. It should operate from left to right. Here is an example: <ul class="menuFirst"> <li><im ...

Keeping extensive files/information on disk in order to alleviate browser memory usage in JavaScript

Currently, I am faced with a challenge involving the encryption of very large files. Unfortunately, my browser keeps crashing due to running out of memory while trying to handle these massive files. To address this issue, I am considering transferring som ...

Learn how to render a dynamic checkbox that is connected with AJAX and PHP for seamless functionality

I need to showcase a dynamic checkbox that can be bound using ajax and php. Here is my code: <?php include 'dbconnect.php'; $result = mysqli_query($link, "SELECT * FROM city where district_id='$dist' "); while($city_row=mysqli_fe ...

Expanding the capabilities of search and replace in Javascript is imperative for enhancing its

I have developed a search and replace function. How can I enhance it by adding a comment or alert to describe the pattern and incorporating a functional input box? Any suggestions are welcome! <html> <head> <title> Search & Replace ...

Is it advisable to implement the modular pattern when creating a Node.js module?

These days, it's quite common to utilize the modular pattern when coding in JavaScript for web development. However, I've noticed that nodejs modules distributed on npm often do not follow this approach. Is there a specific reason why nodejs diff ...

How to position button components at the center in a NextJS application?

Incorporating a button within my nextjs page has been a challenge as I am striving to position it in the center of the page for optimal viewing on both PCs and mobile devices. Despite various attempts, the button remains fixed on the far left side of the p ...

What is preventing the bundling of my CSS into the application?

I'm facing an issue while setting up a new project using vue.js, scss, and webpack (with express.js on the server side and TypeScript). I copied over the configurations from a previous project where everything was working fine. According to my underst ...

Having trouble connecting my chosen color from the color picker

Currently, I am working on an angularJS typescript application where I am trying to retrieve a color from a color picker. While I am successfully obtaining the value from the color picker, I am facing difficulty in binding this color as a background to my ...

Manipulate the inner HTML of a ul element by targeting its li and a child elements using JQuery

Here is the HTML code I am working with: <ul class="links main-menu"> <li class="menu-385 active-trail first active"><a class="active" title="" href="/caribootrunk/">HOME</a></li> <li class="menu-386 active"> ...