user1907509 user1907509 - 1 year ago 46
Node.js Question

Making calls to functions that return promises cleaner

I have two called functions that return promises and I would like to make it cleaner by possibly having on catch statement to catch the errors.

I think I am doing it the right way although the code does call the functions in the correct order asynchronously.

These are my calls:

// The text is hopefully the email address and the pin number

// Set the new state to 'get_city'

}).catch(function(v) {
// Rejection
// If there was an error then prompt the user to enter again
}); // setState


});// verifyEmailPin

And this the actual function - for setState, I haven't yet written the code for the verifyEmailPin function but it follows the same structure as the set state in terms of passing back resolve or reject.

* Function : setState
* Purpose : Set the state to what every is send in on the parameter
exports.setState = function(fbid,newstate){

var success = 'Y';
return new Promise((resolve, reject) => {

client.hmset(fbid, { 'state': newstate });

// Check that we have set it ok

if (err || reply != newstate) {
return reject(err);

return resolve(success);


}).catch(function(v) {



Answer Source

You can use only one .catch at the end. And to have less indentation you could chain the .then

Here's a short example:

function promiseTest(x) {
    Promise.resolve(x).then(function(a) {
        if (typeof x != "number") throw "NaN";
        return a*2;
    }).then(function(a) {
    }).catch(function(err) {
        console.error("error in promise:", err);
promiseTest(1); //logs 2 to the console
promiseTest("a"); // shows error message in the console