Skip to content

Instantly share code, notes, and snippets.

@jekku
Last active August 3, 2017 07:53
Show Gist options
  • Save jekku/30bc04a4f0d992708ec7 to your computer and use it in GitHub Desktop.
Save jekku/30bc04a4f0d992708ec7 to your computer and use it in GitHub Desktop.

Promises and Async.js

Sometimes, you want to execute a function in different parameters at the same time.

Using async :

let jobs;

function parallel_function (callback, filter, param1, param2) {
      mysql.use('some_db')
        .query(
            /*some query that uses a filter and other params for WHERE*/,
            filter,
            callback
        )
        .end()
}

function generic_callback (err, result) {
    if (err) {
        return /*something something*/;
    }
    
    //do something with the accumulated results.
}

//collection came from some magical land.
jobs = _(collection).reduce( (result, item) => {
    result.push(parallel_function.bind(null, item.filter, item.param1, item.param2);
    return result;
}, []);

async.parallel(jobs, generic_callback);

Using Promises :

let jobs;

function parallel_function (filter, param1, param2) {
    return new Promise ( (resolve, reject) => {
        mysql.use('some_db')
            .query(
                /*some query that uses a filter and other params for WHERE*/,
                filter,
                (err, result) => {
                    if (err) {
                        return reject(err);
                    }
                       
                    resolve(result);
                }
            )
            .end();
    });
}

jobs = _(collection).reduce( (result, item) => {
    result.push(parallel_function(item.filter, item.param1, item.param2));
    return result;
}, []);

Promise.all(jobs).then(/* do something with the result here*/);

Notice how Promises avoid the use of "bind" by allowing the function to accept parameters as is.

However, there is more simplicity in using Async by intuition

AND

The callback within the promise is hard to factor out.

Which might mean that using Promise.all() for parallel work might be wrong because it did not eliminate the use of callbacks completely.

How do I correct this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment