Filtering an array with a function that returns a promise

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

    For production purposes you probably want to use a lib like lodasync:

    import { filterAsync } from 'lodasync'
    
    const result = await filterAsync(async(element) => {
      await doSomething()
      return element > 3
    }, array)
    

    Under the hood, it maps your array by invoking the callback on each element and filters the array using the result. But you should not reinvent the wheel.

提交回复
热议问题