Using a promise as a filter callback in JavaScript: A guide

UPDATE: The solution can be found below

I have a multitude of components that need to be filtered based on certain properties, but I am encountering an issue where I cannot resolve the promise before using it in the Array.filter() method.

Here is my current approach:

session.on("message_create", (msg) => {
  const matcher = new Matcher(msg);

  components
    .filter((c) => c.trigger == "message_create")
    .filter((c) => matcher.alias(c.alias))
    .filter(async (c) => await matcher.scope(c.scope))
    .forEach((c) => c.template(msg));
});

I am uncertain, but I believe unresolved promises always evaluate to true... is that correct?

Here is the code for matcher.scope()

async scope(pattern?: string): Promise<boolean> {
  const chat = await this._msg.getChat();
  const contact = await chat.getContact();

  pattern = pattern ?? "anywhere";

  if (pattern == "anywhere") {
    console.log("anywhere");
    return true;
  }

  if (pattern == "group_only" && contact.isGroup) {
    console.log("group_only");
    return true;
  }

  if (pattern == "private_only" && contact.isUser) {
    console.log("private_only");
    return true;
  }

  return false;
}

If you can assist me in reducing the number of conditions, it would greatly benefit me. Thank you

UPDATE: I've marked this question as a duplicate as the original post provided valuable input in resolving my issue. It is still a work in progress, but I've made good progress so far

Initially, I attempted to create a method for filtering arrays using async functions as callbacks by returning "this" for method chaining. However, this turned out to be more complicated than anticipated, requiring a lot of '.then' or 'await' calls.

Subsequently, I tried implementing an "interface" where a synchronous function would handle the method chaining logic by building the ".then" structure and returning 'this'

Here is the final implementation:

class Handler {
  constructor(array) {
    this.array = array
    this.queue = Promise.resolve(this.array)
  }

  async asyncFilter(acall, array) {
    let aux = []

    for (let item of array)
      await acall(item) && aux.push(item)

    return aux
  }

  filter(acall) {
    this.queue = this.queue.then(array => this.asyncFilter(acall, array))

    return this
  }

  async resolve() {
    let aux = await this.queue
    this.queue = Promise.resolve(this.array)

    return aux
  }
}
async function main() {
  let handler = new Handler([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

  let result1 = handler
    .filter(elem => elem % 2 == 0)
    .filter(elem => elem > 5)

  console.log(await result1.resolve())

  let result2 = handler
    .filter(async elem => elem % 2 != 0)
    .filter(async elem => elem > 5)

  console.log(await result2.resolve())

  let result3 = handler
    .filter(elem => elem % 2 != 0)
    .filter(elem => elem < 5)

  console.log(await result3.resolve())
}

main()

And that is the output

PS C:\Users\Smith\Desktop\Javascript\Async> node .\main.js
[ 6, 8, 10 ]
[ 7, 9 ]
[ 1, 3 ]

I am grateful to those who tried to assist me. I will continue to refine my code, handle errors, and so forth. That's all, thank you everyone

Answer №1

async checkScope(pattern: string = 'anywhere'): Promise<boolean> {
  try {
    const chat = await this._msg.getChat();
    const contact = await chat.getContact();

    return pattern === 'anywhere' || pattern == "group_only" && contact.isGroup || pattern == "private_only" && contact.isUser; 
  } catch (err) {
    return false; // return false if any of the promises failed
  }
}

For the primary function

session.on("message_create", async (msg) => { // make this function asynchronous

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

How can I dynamically update a div without refreshing the page by using an onclick event on a

When working on my project, I found helpful insights from this Stack Overflow thread. The structure of template-comparison.php involves fetching code from header.php to ensure the page displays properly. However, the actual "fetch code" process remains un ...

Utilizing Fullcalendar Qtip to display information on mouseover rather than utilizing the eventRender

I have a challenge with integrating Qtip to the eventMousever event instead of the eventRender event in fullcalendar. The main reason for this adjustment is due to the server hosting the data being located in another country, resulting in significant late ...

What steps should I take to address the error message "TypeError: express-validator is not a function

I am currently utilizing express-validator version 6.4.0 and encountering an error when running the server. I have attempted to implement custom validation by organizing separate files for validator, controller, and routes. Here is the primary server file ...

Sending an Ajax request following validation with jQuery

After successfully validating a form, I attempt to make an ajax request. Strangely, if I remove the , after url: 'loginprivate.php', the PHP code functions properly but the validation does not. On the other hand, if I add the ,, the validation wo ...

Error 400 encountered when attempting to log in with React through Google on mobile devices

Currently, I am implementing the React Google Login package to handle user authentication on my website. Surprisingly, it functions perfectly on desktops; however, when tested on mobile devices, an annoying Error 400: redirect_uri_mismatch pops up. Despi ...

Is there a way to retrieve the Angular-Redux store in a child module?

Within my Angular application, I utilize angular-redux for managing the application state. In my main module, I have defined the redux store in the following manner: export class MainModule { constructor(private ngRedux: NgRedux<MainAppState>, ...

Sophisticated method for arranging three integers in javascript in descending order, followed by analyzing their relative distances

In developing an interactive infographic, I am working with three integers assigned to variables, each ranging from 0 to 50000. These numbers often have values that are close to each other, and I am looking for a way to identify when either 2, all 3, or no ...

Using asynchronous file uploading with jQuery and ASP.NET for a seamless user experience

I recently came across an article on Async file upload in ASP.NET which you can find here. Although the process was working fine up until the .ashx file call, I encountered an issue where "context.Request.Files.Count" showed 0. Any help or suggestions wo ...

Guide to displaying an input box depending on the selection made in a Mat-Select component

I am working on a mat-select component that offers two options: Individual Customers and Organizational Customers. When selecting Individual Customers, the dropdown should display three options: First Name, Last Name, and Customer Id. However, when choosin ...

Highest Positioned jQuery Mobile Section

Requesting something a bit out of the ordinary, I understand. I currently have a jQueryMobile page set up with simplicity: <div data-role="page" class="type-home" id="home"> <div data-role="header" data-theme="b"> <h1>Our To ...

Executing a jQuery script on various elements of identical types containing different content (sizes)

I am currently working on a jQuery script that will center my images based on the text block next to them. Since I am using foundation 5, I have to use a jQuery script to override the CSS instead of using vertical-align: middle. The script looks like thi ...

Cancellation of event by keypress handler

I found this code snippet: jQuery('#parent').on('keypress', '.textbox', function(e) { var btn = jQuery(this).closest('tr').find('.btn'); if (btn.length) { btn.triggerHandler('click&apo ...

Switching a component in Mui App transforms the entire aesthetic

I'm currently working on a project using Mui and the Material Kit theme. While I initially tried to customize the default components provided by Material Kit using custom CSS, I found that I was unable to override the styles as expected. Consequently, ...

Trouble arises when attempting to import React JSX project/modules from npm into an AngularJS TypeScript module

In the process of developing a proof-of-concept React framework/library, I aim to create a versatile solution that can be utilized in both React and AngularJS applications. To achieve this goal, I have initiated two separate projects: - sample-react-frame ...

Adjusting ngClass dynamically as values change

Currently, I am facing a situation where I want to dynamically add a class to my view using ngClass based on changes in the output value. The output value is dependent on the response received from an API, and I am fetching data from the endpoint every sec ...

Dynamically showing a div using JavaScript and AJAX after changing the window location

After successfully fetching data from the server through AJAX, I am redirecting to the same screen/URL. Is it possible to show/display a div after redirecting using jQuery? $.ajax({ type: "POST", url: action, data: form_data, success: func ...

The entire DOM refreshes when a user updates the input field

In my React component, I am managing two states: inputText and students. The inputText state tracks the value of an input field, while the students state is an array used to populate a list of student names. The issue arises when the inputText state change ...

Tips for avoiding event listeners from being triggered multiple times

Implemented an event listener on an HTML element that was retrieved by className within the render method of highcharts, but for some reason, the listener is being triggered twice. The issue seems to be with the onClick handler in the highchart's rend ...

Unable to retrieve field values from Firestore if they are numeric rather than strings

I need to display this information in a list format: li.setAttribute('data-id', updatesArgument.id);//'id' here unique id Example 1 name.textContent = updatesArgument.data().count;// Works if String Example 2 let i=1; nam ...

What is the best way to link to this list of options?

#episode-list { padding: 1em; margin: 1em auto; border-top: 5px solid #69c773; box-shadow: 0 2px 10px rgba(0,0,0,.8) } input { width: 100%; padding: .5em; font-size: 1.2em; border-radius: 3px; border: 1px solid #d9d9d9 } <div id="epis ...