0

I was looking at the below block of code. I am trying to understand how can there be a catch without try block in javascript. I understand there is a promise being used, but the create database is within the promise and my understanding is that we should have had the try block surrounding the client.queryAsync.

The below code works fine and I am trying to understand how it works without try block. I also read http://know.cujojs.com/tutorials/async/mastering-async-error-handling-with-promises but the link also shows try block being used.

Can anyone please explain. Thanks in advance

function init(dbName) {
    return util.serialize('Open database', function () {
        return connect(maintenanceDbName).then(function (client) {
            return client.queryAsync('CREATE DATABASE ' + dbName + ' TEMPLATE=template0 ENCODING=\'UTF8\' LC_COLLATE=\'C\' LC_CTYPE=\'C\';').catch(function (err) {
                // Already created previously, which is fine
                if (err.message.indexOf('already exists') < 0) {
                    throw err;
                }
            }).finally(function () {
                return closeDatabase(client);
            });
        }).then(function () {
            return connect(dbName);
        }).then(function (client) {
            db = client;
            return fs.readFileAsync(path.join(__dirname, 'postgresql.sql'), 'utf8').then(db.queryAsync.bind(db));
        });
    });
}
Romaan
  • 2,645
  • 5
  • 32
  • 63
  • 5
    This isn't a real try-catch block, rather a method called `catch` that is provided by a promise library. A real try-catch block looks like `try {} catch (e) {}`. – Qantas 94 Heavy Dec 11 '14 at 01:07
  • FYI: JavaScript allows for `try-finally` blocks (without `catch`). – PM 77-1 Dec 11 '14 at 01:09
  • 1
    related: [Is the 'catch' method name of JS Promises/A+ invalid since it's a JS keyword?](http://stackoverflow.com/q/25774628/1048572) – Bergi Dec 11 '14 at 01:14
  • @Bergi I used .catch method and did not observe that it was not a keyword catch. I did later on. – Romaan Dec 11 '14 at 01:22
  • 1
    FYI, your question is kind of hard to follow because the `.catch()` is off the screen to the right and requires scrolling to find. – jfriend00 Dec 11 '14 at 03:33

1 Answers1

4

Found the answer, the catch used here is not a keyword, it is .catch wrapper function of a promise and can be used to catch any exception that happen within the .then block.

Romaan
  • 2,645
  • 5
  • 32
  • 63