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