Thursday, 1 June 2017

How to properly return value in async function when there are lot of callbacks

I have an async function, that calls other async functions, and when they are all done, I'm returning the results.

I don't wanna use Promise.all, because in case any of these functions fail, I just don't add them to my results.

ATM my code looks like this. It works, but I don't like the new Promise, I wanna do it in ES6 async way, so the callAll function should look like const callAll = async (query) => {

const callAll = (query) => {
    return new Promise((resolve, reject) => {
        const results = [];

        const jobs = [
            {
                promise: someModuleFirst.search(query), 
                done: false
            },
            {
                promise: someModuleSecond.search(query),
                done: false
            },
            {
                promise: someModuleThird.search(query),
                done: false    
            }
        ];

        const areAllDone = () => {
            if(!jobs.filter((job) => !job.done).length) {
                return true;
            }
        };

        jobs.forEach((job) => {
            job.promise.then((result) => {
                job.done = true;

                results.push(result);

                if(areAllDone()) {
                    resolve(results);
                }
            }).catch((error) => {
                job.done = true; 

                if(areAllDone()) {
                    resolve(results);
                }
            });
        });
    });
};



via xerq

No comments:

Post a Comment