Manuel Reis Manuel Reis - 3 months ago 15
TypeScript Question

Catch->Then->Catch example with Bluebird

I am trying to setup my code flow using promises, but I am failing to grasp what is possible to do, and what is not.

Let's say I have a register function, where I want to:

a) register a user
b) log the registering process
c) send an activation email
d) return the answer to the callback

I start by seeing if a user already exists, and if it doesn't, then a

StorageError
is thrown, and caught in the next
catch
block.

let basicRegister = function (request: any, reply: any) {
let seneca = this;
let act = Promise.promisify(seneca.act, { context: seneca });

User.getByEmail(email).then(function (user: any) {
throw new OperationError("Email already exists");
}).catch(StorageError, function (err: any) {
return User.create().catch(function (err: any) {
throw new OperationError(err.message);
});
}).then((user: any) => {
return UserActivity.create().catch(function (err: any) {
throw new OperationError(err.message);
});
}).then(function (confirmationMessage: any) {

//how can I obtain the user object here?

return { ok: true, user: user };
}).catch(OperationError, (error: any) => {
console.log(error);
return { ok: false, message: error.message };
}).asCallback(reply);
}


Based on the code above, I have the following questions:

1 - Is it normal to have catch and then interleaved as in this example? If not, what is the correct approach?

2 - Is it possible to obtain the
user
object from a previous
then
in the final
then
?

Let me know if you need any more information

Answer

For accessing the userobject, you could just continue in the scope where the user object exists.Regarding your error handling: You only need to catch errors at the very end. They get passed through the promise chain anyway.

let basicRegister = function(request: any, reply: any) {
    let seneca = this;
    let act = Promise.promisify(seneca.act, {
        context: seneca
    });

    User.getByEmail(email).then(function(user: any) {
        throw new OperationError("Email already exists");
    }).catch(StorageError, function(err: any) {
        return User.create();
    }).then((user) => {
        return UserActivity.create()
            .then((confirmationMessage) => {
                return {
                    ok: true,
                    user: user
                };
            });
    }).catch(OperationError, (error: any) => {
        console.log(error);
        return {
            ok: false,
            message: error.message
        };
    }).asCallback(reply);
}