【发布时间】:2018-07-19 15:07:15
【问题描述】:
我的代码看起来类似于:
const MyClass {
checkExists: function(db_client) {
return new Promise(fulfill, reject) {
var sql = 'select * from table';
db_client.connect().then(c => {
}).then(res => {
client.release();
fulfill(res.rows[0].col1 === 1 ? true : false);
}).catch(error => {
reject(error);
});
});
}
doSomething: function(db_client) {
return new Promise(fulfill, reject) {
var sql = 'delete from table where x=1';
db_client.connect().then(c => {
}).then(res => {
fulfill();
}).catch(error => {
reject(error);
});
});
}
};
module.exports = MyClass;
var myc = require('./MyClass.js');
myc.checkExists(db_client).then(resp => {
if(resp === true) {
myc.doSomething(db_client).then(resp => {
console.log('success.');
} else {
console.log('we are done.');
}
}).catch(error => {
console.log(error);
});
}).catch(error => {
console.log(error);
});
根据上面的示例,我必须运行一个依赖于另一个查询结果的查询。 (是伪代码,如有错误请见谅)
但是,我注意到它开始导致嵌套的 Promise 或函数调用,其中包含来自另一个 Promise 的实现中的 Promise。
我可以看到这种情况越来越糟。这是犹太洁食吗?有没有更好的方法来思考/处理我正在尝试做的事情?
编辑:
不知道为什么它被标记为一个问题的重复,其中发布者似乎明确意识到反模式并询问如何避免它与反模式/解决方案不知道的问题张贴者,但认识到编程风格中的问题并正在寻求帮助(其中的讨论可能会产生相同类型的解决方案)。
【问题讨论】:
-
移除内部catch,将inner.then移出一个作用域(在.catch()之前,并返回内部.doSomething
-
foo().then(() => bar()).then(() => foobar()).then(allDone).catch(handleError)
标签: javascript node.js promise