This are the asynchronous versions of some()
and every()
that I came up with
someAsync()
Array.prototype.someAsync = function (callbackfn) {
return new Promise(async (resolve,reject) => {
await Promise.all(this.map(async item => {
if (await callbackfn(item)) resolve(true)
})).catch(reject)
resolve(false)
})
}
// Examples
['',0,undefined,false].someAsync(async e=>e).then(e=>console.log(e)) // false
['',0,undefined,false,true].someAsync(async e=>e).then(e=>console.log(e)) // true
everyAsync()
Array.prototype.everyAsync = function (callbackfn) {
return new Promise(async (resolve,reject) => {
await Promise.all(this.map(async item => {
if (! await callbackfn(item)) resolve(false)
})).catch(reject)
resolve(true)
})
}
// Examples
[[],{},1,true].everyAsync(async e=>e).then(e=>console.log(e)) // true
[[],{},1,true,false].everyAsync(async e=>e).then(e=>console.log(e)) // false
Disadvantages
- They only accept the callback and with one argument only
- Even though
someAsync()
resolves true
as soon as a truthy value is resolved and everyAsync()
resolves false
as soon as a falsy value is resolved, the callback is still executed till the end for every element, even if the method's promise has already resolved. I think this has no straightforward solution as long as promises are not cancellable