无需尝试使用JavaScript并承诺

时间:2014-12-11 01:04:00

标签: javascript try-catch promise

我正在查看下面的代码块。我试图了解如何在javascript中没有try块的情况下捕获。我知道有一个使用的承诺,但创建数据库在承诺范围内,我的理解是我们应该有一个围绕client.queryAsync的try块。

下面的代码工作正常,我试图了解它是如何工作的,没有try块。我还阅读了http://know.cujojs.com/tutorials/async/mastering-async-error-handling-with-promises,但该链接还显示了正在使用的try块。

任何人都可以解释一下。提前致谢

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));
        });
    });
}

1 个答案:

答案 0 :(得分:1)

找到答案,此处使用的catch不是关键字,它是承诺的.catch包装函数,可用于捕获.then块内发生的任何异常