Filtering an array based on asynchronous or promise-based conditions

Looking to filter an array based on a condition that requires asynchronous checking.

return someList.filter(function(element){ 
   //async process here
})

Any better way to achieve this using promises?

This code snippet utilizes Q for handling promises, but it can be adapted to any other promises implementation as well.

return q.all(someList.map(function (listElement) {
        return promiseMeACondition(listElement.entryId).then(function (condition) {
            if (condition) {
                return q.fcall(function () {
                    return listElement;
                });
            } else {
                return q.fcall(function(){});
            }
        });
    }));

The above code snippet successfully resolves the promises and filters the array accordingly.

Answer №1

If you're using libraries such as Bluebird, you'll find convenient methods like .map and .filter for promises already built-in. Your overall approach seems correct, but don't forget to add an Array.prototype.filter at the end to remove any "bad results." For instance, use a BadValue constant for resolving and filter out elements equal to it.

var BadValue = {};

return q.all(someList.map(function (listElement) {
        return promiseMeACondition(listElement.entryId).then(function (listElement) {
            return (condition(listElement)) ? listElement : BadValue;
    })).then(function(arr){
            return arr.filter(function(el){ return el !== BadValue; });
    });

When using Bluebird:

  Promise.filter(someList, condition);

You could also abstract this functionality into a standalone filter function specifically for promises.

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

What is the best way to refresh a page using Vue 3 Composition API and router?

Once confirmed in Vue 3 Composition API router.push('/IssueList'); When arriving at the IssueList page, I want my issue-incoming and issue-send components to refresh. Although I am redirecting to the page, the IssueList page does not refresh. ...

Create a JavaScript function that can identify when a click event occurs within an li

I encountered a situation like this where I have code snippets from a website that I don't have permission to modify. <li class="History_lisitem_logout ui-last-child" data-icon="power"> <a id="History_lisitem_logout" ...

Dynamically Generate Nested Objects in JavaScript

I have an object that is currently empty and I am looking to dynamically create a nested object within it. const obj = {} obj["test1"]["test1.1"] = x //initialize to some variable However, I encountered this error message: Uncaught Typ ...

I'm looking to enhance my skills by learning how to implement the edit data method in ReactJS using Formik and Axios. Can

Hey there! I'm trying to figure out how to implement an edit or update function within the same component using reactjs hooks, formik, and axios. I've successfully created an add function, but I'm struggling with the edit function as the for ...

Comparing Array Elements within a Function

As I embark on my C class, a common yet perplexing question arises regarding the implementation of comparing elements within two variable-length arrays in a separate function. The task at hand is to identify and extract any shared elements found in both ar ...

Struggling to eliminate placeholders using regular expressions in JavaScript

In my dynamically generated table, I have some placeholders that need to be removed. These placeholders are in the format of {firm[i][j]}, where i and j are numbers. I attempted to use a regular expression in JavaScript to remove them, but it didn't ...

Guide to retrieving data from a URL and storing it in a string variable with JavaScript

Attempting to retrieve the JSON data from a specific URL and store it in a variable. The code snippet below successfully loads the JSON into a div element: $("#siteloader").html('<object data="MYURL">'); However, the goal is to extract t ...

The issue with Vue Router is that it fails to display the intended component

I am facing an issue with nested routes in vue-router, specified in the router.js file. After logging in, the Query and Result links in the Header section always display the Register and Login components, even though my Vuex setup seems correct based on my ...

Switchable radio options

Currently, I am creating a form containing multiple options that are mutually exclusive. However, none of these options are mandatory. That is why I want to enable the user to uncheck a selected radio button by simply clicking on it again. This way, all th ...

What is the best way to implement a callback in JavaScript (Node) in order to ensure that an asynchronous function finishes before moving on

I have a function called translateCommand(command) that uses a Translate package from npm to translate some text into a different language. The issue arises because the translate function provided by that package is asynchronous, causing the translateComma ...

The button press does not seem to be functioning

I am facing an issue with a button located on a modal pop up window. The click event of the button does not seem to be firing. This button is placed within a gridview. Strangely, when I place the button outside the gridview it works perfectly, but inside ...

Numerous instances of Codemirror

I have the ability to generate and exhibit multiple dynamic codemirror instances, however, I am having trouble referencing them using the code snippet below. I suspect that the problem lies in creating a dynamic function name (not entirely sure how to ac ...

Creating a list using data from a text file with the help of BufferedReader

Currently, I am in the process of creating a program that reads and formats recipe information from a text file. As part of this project, I have implemented a loop to iterate through the contents of the file. However, I have encountered an issue with the r ...

Does the positive Z axis move inward in threejs? The behavior of camera.near and camera.far seems strange

My goal is to display only a slice of my 3D object. I have tried setting the orthographic camera's camera.near to 2.0 and camera.far to 1.5, then iterating with values of camera.near = 1.5 and camera.far = 1.0. However, this approach is not yielding t ...

What could be the reason for my user input not being captured and saved as variable data on the HTML webpage?

Here is the code I am working with: var g = document.getElementById("al").value; function start() { document.getElementById("test2").innerHTML = typeof(g) + parseFloat(g); } <p id="test2">Output will be displayed here:</p> <form> ...

Retrieving FormData() parameters sent via Ajax with PHP

After successfully testing FormData() with jQuery.ajax, I encountered a roadblock when trying to implement a progress bar for file uploads using the same method. This led me to use AJAX directly and post form data, but unfortunately, retrieving the form da ...

Moving in a circular motion around a certain point creates unexpected bugs in THREE.js

All of the elements in my scene are structured as a chain of three Object3Ds. The hierarchy goes from parent to child in the order of cellPivot -> modifier -> setup The purpose of setup is to permanently align a loaded object by resizing it or provi ...

What is the process for activating an event when there is a modification in the content of

Here is the element I'm working with: <div id="upload_area"> Images </div> I need a way to trigger an event if the content inside <div id="upload_area"> changes dynamically (for example, from 'Images' to 'P ...

What steps should I take to incorporate the delete feature as described above?

Click here to access the delete functionality Hello there, I need help implementing a delete function similar to the one provided in the link above. Below is the code snippet for your reference. I am utilizing the map method to extract data from an array ...

Exploring the combination of Holder.js and Rails routes

What's the best way to integrate Holder.js into my Rails application? I'm running into issues where Rails is interpreting the parameters passed to the script as routes and returning 404 errors. Has anyone successfully implemented this before? ...