Jordan Jordan - 2 months ago 16
Node.js Question

Q promise - how to use it?

I am new to Node and want to call a function and determine whether or not to call the next function based on the results of the first function. The functions are asynchronous so the results are not immediately known. The following code works fine but now I want to add more asynchronous functions and chain them all together.

var doSomething = require('./custom-module1.js'); //returns a boolean
var doAnotherThing = require('./custom-module2.js'); //returns a double

var var1 = process.argv[2];
var var2 = process.argv[3];
var var3 = process.argv[4];

doSomething(var1, var3, function(data) {
if (data) {
doAnotherThing(var1,var2, function(data){
console.log(var1 + ' is value: ' + data);
});
}
});


I want to make the code something like this using promises.

getListOfStuff()
.then(
for(i=0;i<data.length;i++) {
doSomething(data[i], var3)
.then(
if (doSomething returns true) {
doAnotherThing(data[i], var2)
.then(doYetAnotherThing(data[i]))
.then(andEvenMoreThingsToBeDone(data[i]))
}
);
}
);


I read about q and using denodefiy but I can't understand the syntax to make it work. Would it be best to modify my custom modules to return promises so they would be inherently thenable? I get the concept but not the syntax, how do I actually do it?

I tried to denodeify using the following 2 different notations.

var doSomethingDN = Q.denodeify(doSomething);
var doAnotherThingDN= Q.denodeify(doAnotherThing);

doSomethingDN(var1, var3)
.then(
if(!data) {
doAnotherThingDN(var1,var2)
}
);


And this one

var doSomethingDN = Q.nfbind(doSomething);
var doAnotherThingDN= Q.nfbind(doAnotherThing);

doSomethingDN (var1, var3)
.then(
if(!data) {
doAnotherThingDN(var1,var2)
}
);


The if get's an unexpected token error. If I remove then both run but the boolean result from doSomething isn't able to control the program flow.

Answer

You still need to use a callback function with promises:

doSomethingDN (var1, var3)
.then(function(data) {
//    ^^^^^^^^^^^^^^^^
    if (!data) {
        return doAnotherThingDN(var1,var2)
    }
}); /*
^

You were getting a syntax error because you put the function body right as the argument to then.

Comments