How to use Array.prototype.filter with async?

前端 未结 5 1828
闹比i
闹比i 2020-12-29 01:56

Background

I am trying to filter an array of objects. Before I filter, I need to convert them to some format, and this operation is asynchronous.

         


        
5条回答
  •  清酒与你
    2020-12-29 02:05

    Use Scramjet fromArray/toArray methods...

    const result = await scramjet.fromArray(arr)
                                 .filter(async (item) => somePromiseReturningMethod(item))
                                 .toArray();
    

    as simple as that - here's a ready example to copy/paste:

    const scramjet = require('../../');
    
    async function myAsyncFilterFunc(data) {
        return new Promise(res => {
            process.nextTick(res.bind(null, data % 2));
        });
    }
    
    async function x() {
        const x = await scramjet.fromArray([1,2,3,4,5])
            .filter(async (item) => myAsyncFilterFunc(item))
            .toArray();
        return x;
    }
    
    x().then(
        (out) => console.log(out),
        (err) => (console.error(err), process.exit(3)) // eslint-disable-line
    );
    

    Disclamer: I am the author of scramjet. :)

提交回复
热议问题