Filtering an array with a function that returns a promise

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

    There is a one liner to to do that.

    const filterPromise = (values, fn) => 
        Promise.all(values.map(fn)).then(booleans => values.filter((_, i) => booleans[i]));
    

    Pass the array into values and the function into fn.

    More description on how this one liner works is available here.

提交回复
热议问题