I have a JavaScript class with some async functions inside.
If there is a number greater than 10 in this array I expect the .some() function to return true, but if the array contains no numbers larger than 10 I expect it to return false.
The issue I'm having is that the function call is always returning true whether or not there is a number greater than 10 in the array.
class Blah {
async doStuff() {
const nums = [1, 2, 3, 4, 5, 6];
const asyncResult = await nums.some(async num => {
if (num > 10) {
const allowed = await this.isAllowed(num);
if (allowed) {
return true;
}
}
});
console.log(asyncResult);
}
async isAllowed(num) {
console.log(`${num} is in the array`);
return true;
}
}
const b = new Blah();
b.doStuff(); // This return true but it should be returning false
This currently returns true but as you can see the array does not have a number larger than 10
If I remove the async from inside the .some() function then it seems to work, but that function needs to be async because I need to await on the this.isAllowed function call and that is also an async function.
The problem:
Your some handler is an async function. Async functions always return promises, which are considered truthy. E.g. !!new Promise(() => {}) === true.
The solution:
Instead, you could use Promise.all. Iterate through each num, if any pass your condition, resolve true the return promise. If Promise.all completes (i.e., you've checked all nums) and the returned promise hasn't already been resolved (i.e. none of the nums passed your condition), then resolve false (or reject) your return promise.
class Blah {
doStuff(nums) {
return new Promise((resolve, reject) => {
let promises = nums.map(async num => {
if (num > 10 && await this.isAllowed(num))
resolve(true);
});
Promise.all(promises).then(() => resolve(false));
});
}
async isAllowed(num) {
console.log(`${num} is in the array`);
return true;
}
}
const b = new Blah();
b.doStuff([1, 2, 3, 4, 5, 6]).then(value => console.log(value));
b.doStuff([1, 2, 3, 4, 5, 20]).then(value => console.log(value));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With