Filtering an array with a function that returns a promise

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

    Promise Reducer to the rescue!

    [1, 2, 3, 4].reduce((op, n) => {
        return op.then(filteredNs => {
            return new Promise(resolve => {
                setTimeout(() => {
                    if (n >= 3) {
                        console.log("Keeping", n);
                        resolve(filteredNs.concat(n))
                    } else {
                        console.log("Dropping", n);
                        resolve(filteredNs);
                    }
                }, 1000);
            });
        });
    }, Promise.resolve([]))
    .then(filteredNs => console.log(filteredNs));
    

    Reducers are awesome. "Reduce my problem to my goal" seems to be a pretty good strategy for anything more complex than what the simple tools will solve for you, i.e. filtering an array of things that aren't all available immediately.

提交回复
热议问题