I have code that looks something similar to:
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);
});
Per the example above, I have to run a query that is dependent upon the result of another query. (It's pseudocode, forgive if I made mistakes)
However, I'm noticing that it starts to result in nested Promises or function calls with promises from within the fulfillment of another Promise.
I can see this getting worse and worse. Is this kosher? Is there a better way to think/handle what I'm trying to do?
Edit:
Not sure why it's being marked as a duplicate of a question where the poster seems to be explicitly aware of an anti-pattern and is asking how to avoid it vs. a question where the anti-pattern/solution is not known by the poster, but recognizes an issue in a programming style and is looking for help (in which the discussion may result in the same type of solution).