javascript - How do you prevent nested queries/catches in sequelize? -


i think i'm preventing nested queries as possible, i'm not sure. understand calls here can executed in single select query, did simplify example.

// example in typescript  // find user user.find({where:{username:'user'}})      // if found user     .then(function(user) {          return user.find({where:{username:'other_user'}})              // if found other_user             .then(function(other_user) {                 // stuff                 return whatever_i_need             }              // if went wrong, go straight parent catch             .catch(function(err) {                 // stuff                 throw new error()             }     }      // if previous .then() returned success     .then(function(data) {          return user.find({where:{username:'yet_another_user'}})              // if found yet_another_user             .then(function(yet_another_user) {                 // stuff                 return whatever_i_need_again             }              // if went wrong, go straight parent catch             .catch(function(err) {                 // stuff                 throw new error()             }     }      // if threw error @ point in time     .catch(function(err) {         // handle error     } 

however, results in nested promises, promises meant prevent. "max depth" recommended promises, or missing something? there better way chain queries?

return nested promise instead of handling in inner blocks flatten structure.

user.find({where:{username:'user'}}) .then(function(user) {   if (user) { // if found user     // stuff     return user.find({where:{username:'other_user'}});   }   throw new error('user not-found'); }) .then(function(other_user) {   if (other_user) { // if found other_user     // stuff     return whatever_i_need;   }   throw new error('other_user not-found'); }) .then(function(data) {   return user.find({where:{username:'yet_another_user'}}) }) .then(function(yet_another_user) {   if (yet_another_user) { // if found yet_another_user     // stuff     return whatever_i_need_again;   }   throw new error('yet_another_user not-found'); } .then(function(data){   // stuff }) .catch(function(err) { // if threw error @ point in time   // handle error } 

note resolved promise means query done. that's about. successful query does't guarantee results returned. empty result valid outcome of resolved promises.

note return value resolve or reject callback wrapped resolved promise, , passed next then block, making meaningful promise chain. @matt's follow-up feedback below regarding point.


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -