Node.js and Q Promises: How can I hand over parameters in a cleaner way?

118 views Asked by At

I have some code like this:

function example(data){
    asyncFnOne()
        .all([asyncFnTwo(), data])
        .spread(asyncFnThree)
        .done();
};

It doesn't matter what those functions do. The problem I have is that I don't know how asyncFnThree can access both data from asyncFnTwo and from the function parameters. The way I solved the problem is not very readable. Is there a recommended way to do this in a clean way?

A second possible soultion would be

function example(data){
    asyncFnOne()
        .then(asyncFnTwo)
        .then(function(result){
            asyncFnThree(result, data);
        })
        .done();
    };
};

But I think it is even less readable.

2

There are 2 answers

0
Bergi On BEST ANSWER

To use Q.all in the desired way you'd have to do the following:

function example(data) {
    return Q.all[
        asyncFnOne().then(asyncFnTwo),
        data
    ]).spread(asyncFnThree);
}

Or use a variable for the first part of the chain, so that you don't have to stuff everything in one expression and could use return Q.all([promiseTwo, data])….

The alternative way with the closure is totally fine as well, and rather standard. You might as well use any library that offers some kind of partial application, and use that instead of the function expression.

function example(data) {
    return asyncFnOne()
    .then(asyncFnTwo)
    .then(asyncFnThree.bind(null, data)); // argument order to asyncFnThree: data, result
}
1
MoD On

You can use variables as buffers or create some "middle-man" promises. You can find some good examples here: http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html?utm_source=javascriptweekly&utm_medium=email