K the Kelvin
K the Kelvin

Reputation: 102

How to escape from .then() without executing the next statement in Express Js Promise?

By using mysql2 with promise, I have the controller.js as below :

exports.company_add = (req, res) => {
    company_model.company_add(admin_email, admin_info).then((result) => { ... })
    .catch((err) => { ... })
}

And the model.js as below :

exports.company_add = (admin_email, admin_info) => {
    return new Promise((resolve, reject) => {
        connectionPool.getConnection((connectionError, connection) => {
        if (connectionError) reject(connectionError);
        return connection.promise().query('SELECT * FROM admin WHERE admin_email = ?', [admin_email])
            .then(([rows, field]) => {
                if (rows.length) reject('Email exist');
                else return connection.promise().query('INSERT INTO companydb.admin SET ?', [admin_info])
            })
            .then((result) => {
                console.log('result')
                if (result[0].affectedRows === 1) resolve(result);
                else reject('INSERT FAIL');
            })
            .catch((err) => {
                reject(err);
            })
            .finally(() => {
                connection.release();
            })
    });
    });
};

I wonder how I escape from the .then() statement when the line if (rows.length) occurred, since there is no need to continue with the next .then() for this case if the email already exist in the database. Do I need to throw it and add a .catch() just before the next .then() executed?

Upvotes: 1

Views: 337

Answers (1)

Bergi
Bergi

Reputation: 665456

One cannot really break out of a then chain other than by nesting or throwing an exception. Yes, in this case you probably should throw, but you don't need to .catch it when you avoid the Promise constructor antipattern and just make it a chained promise:

exports.company_add = (admin_email, admin_info) => {
    return connectionPool.getConnection().then(connection => {
        return connection.promise().query('SELECT * FROM admin WHERE admin_email = ?', [admin_email])
        .then(([rows, field]) => {
            if (rows.length)
                throw new Error('Email exist');
            else
                return connection.promise().query('INSERT INTO companydb.admin SET ?', [admin_info])
        })
        .then((result) => {
            console.log('result')
            if (result[0].affectedRows !== 1)
                throw new Error('INSERT FAIL');
            return result;
        })
        .finally(() => {
            connection.release();
        })
    }, err => {
        console.error(err);
        throw new Error('CONNECTION FAIL');
    });
};

Upvotes: 1

Related Questions