Filtering an array with a function that returns a promise

前端 未结 15 1400
遇见更好的自我
遇见更好的自我 2020-11-28 13:22

Given

let arr = [1,2,3];

function filter(num) {
  return new Promise((res, rej) => {
    setTimeout(() => {
      if( num === 3 ) {
        res(num);
         


        
15条回答
  •  情书的邮戳
    2020-11-28 13:39

    A valid way to do this (but it seems too messy):

    let arr = [1,2,3];
    
    function filter(num) {
      return new Promise((res, rej) => {
        setTimeout(() => {
          if( num === 3 ) {
            res(num);
          } else {
            rej();
          }
        }, 1);
      });
    }
    
    async function check(num) {
      try {
        await filter(num);
        return true;
      } catch(err) {
        return false;
      }
    }
    
    (async function() {
      for( let num of arr ) {
        let res = await check(num);
        if(!res) {
          let index = arr.indexOf(num);
          arr.splice(index, 1);
        }
      }
    })();
    

    Again, seems way too messy.

提交回复
热议问题