Filtering an array with a function that returns a promise

前端 未结 15 1387
遇见更好的自我
遇见更好的自我 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:50

    Here's a shorter version of @pie6k's Typescript version:

    async function filter(arr: T[], callback: (val: T) => Promise) {
      const fail = Symbol()
      const result = (await Promise.all(arr.map(async item => (await callback(item)) ? item : fail))).filter(i => i !== fail)
      return result as T[] // the "fail" entries are all filtered out so this is OK
    }
    

提交回复
热议问题