skip to Main Content

If I need to check value inside array or not, then I will use includes,

let orig_arr = [1,2,3];
let input = 1;
if (orig_arr.includes(input)) {
  // ...
}

If wanna do async way then user for await loop

for await (let el of orig_arr) {
  if (el == input) {
    // ...
  }
}

But because it has more wrap, so I will use flag like below, or just write a lib calling it with async

let flag = false;
for await (let el of orig_arr) {
  if (el == input) {
    flag = true;
  }
}
if (flag) {
  // ...
}
lib_array_include_async = (reqArray, reqItem) => {
   return new Promise((resolve, reject) => {
    (async () => {
      // ...
    })();
  });
};
// await lib_array_include_async(reqArray, reqItem)

Is there any shorter way , original javascript function, syntax can do same thing to check value inside array or not with async ?
like for let loop just add await simply become async

2

Answers


  1. You could get an async iterator for an array.
    You have to wait the async iterators helper some() otherwise implement it yourself.
    https://github.com/tc39/proposal-async-iterator-helpers

    A polyfil could be like that:

    const AsyncIteratorPrototype = Object.getPrototypeOf(
      Object.getPrototypeOf(Object.getPrototypeOf((async function* () {})())),
    );
    
    AsyncIteratorPrototype.some = async function(cb){
      for await(const item of this){
        if(await cb(item)) return true;
      }
      return false
    };
    
    async function* arrayToAsync(arr){
      for(const item of arr){
        yield item;
      }
    }
    
    
    arrayToAsync([1,2,3,4,5]).some(num => num === 5).then(out => console.log(out));
    Login or Signup to reply.
  2. I guess the OP could want to check an array item existence with async code item-by-item.
    For that you either create a custom promise queue or use for await again.
    If your item check callback doesn’t use a shared state between invocations you could use just
    Promise.any to resolve all callbacks simultaneously:

    const arr = [1,2,3,4,5];
    
    
    Promise.any(arr.map(async item => {
       
       await new Promise(resolve => setTimeout(resolve, Math.random()*300));
       
       if(item === 5){
        return true;
       }
       
       throw new Error('not equal');
      
    })).then(() => console.log('found')).catch(() => console.error('not found'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search