给定:
- NodeJS v0.10.25
- 已启用所有 Harmony 功能
“使用严格”
以及以下代码:
db.connect({
host: DB_HOST,
port: DB_PORT
}).then(function(dbConn) {
console.log('DBASE connected to ' + DB_HOST + ':' + DB_PORT);
db.dbList().run(dbConn).then(function(result) {
if (result.indexOf(SCRIPT_NAME) == -1) throw new Error('unable to locate database ' + SCRIPT_NAME);
dbConn.use(SCRIPT_NAME);
console.log('DBASE bound to ' + SCRIPT_NAME + ' on ' + DB_HOST + ':' + DB_PORT);
db.tableList().run(dbConn)
.then(function(result) {
if (!result) throw new Error(SCRIPT_NAME + ' unable to enumerate tables');
if (!result.length) throw new Error(SCRIPT_NAME + ' has no tables');
console.log('DBASE ' + DB_HOST + ':' + DB_PORT + '/' + SCRIPT_NAME + ' has ' + result.length + ' table' + ((result.length > 1) ? 's' : ''));
}).catch(function(err) {
console.error('DBASE ' + err);
});
}).catch(function(err) {
console.error('DBASE ' + err);
});
}).catch(function(err) {
console.error('DBASE ' + err);
});
注意多个相同的 catch block :
.catch(function(err) {
console.error('DBASE ' + err);
});
是否有推荐/接受/事实上的方法来跨多个级别的控制结构重用该异常处理程序?
最佳答案
错误会冒泡直到被捕获,因此您不需要多次捕获,并且可以通过链接 promise 而不是嵌套它们来使代码更具可读性:
db.connect({
host: DB_HOST,
port: DB_PORT
}).then(function(dbConn) {
console.log('DBASE connected to ' + DB_HOST + ':' + DB_PORT);
// it's important to return if you have a promise so the chain doesn't break
return db.dbList().run(dbConn);
}).then(function(result) {
if (result.indexOf(SCRIPT_NAME) == -1) throw new Error('unable to locate database ' + SCRIPT_NAME);
dbConn.use(SCRIPT_NAME);
console.log('DBASE bound to ' + SCRIPT_NAME + ' on ' + DB_HOST + ':' + DB_PORT);
return db.tableList().run(dbConn);
}).then(function(result) {
if (!result) throw new Error(SCRIPT_NAME + ' unable to enumerate tables');
if (!result.length) throw new Error(SCRIPT_NAME + ' has no tables');
console.log('DBASE ' + DB_HOST + ':' + DB_PORT + '/' + SCRIPT_NAME + ' has ' + result.length + ' table' + ((result.length > 1) ? 's' : ''));
}).catch(function(err) {
console.error('DBASE ' + err);
});
关于node.js - 对多个 then 方法使用相同的 catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34795381/