Filtering an array with a function that returns a promise

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

    Late to the game but since no one else mentioned it, Bluebird supports Promise.map which is my go-to for filters requiring aysnc processing for the condition,

    function filterAsync(arr) {
        return Promise.map(arr, num => {
            if (num === 3) return num;
        })
            .filter(num => num !== undefined)
    }
    

提交回复
热议问题