【发布时间】:2016-08-29 02:21:11
【问题描述】:
我认为我正在尽可能地防止嵌套查询,但老实说我不确定。我知道这里的调用都可以在单个选择查询中执行,但我这样做是为了简化示例。
// This example is 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) {
// do stuff
return whatever_i_need
}
// if something went wrong, go straight to parent catch
.catch(function(err) {
// do 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) {
// do stuff
return whatever_i_need_again
}
// if something went wrong, go straight to parent catch
.catch(function(err) {
// do stuff
throw new Error()
}
}
// if anything threw an error at any point in time
.catch(function(err) {
// handle the error
}
但是,这会导致嵌套的 Promise,而这正是 Promise 所要防止的。这是为承诺推荐的“最大深度”,还是我错过了什么?有没有更好的方法来链接查询?
【问题讨论】:
-
this results in nested promises, which is exactly what promises are meant to prevent.- 在某些情况下需要嵌套承诺。不是说这是这样的情况,但不要盲目相信你读到的关于 Promises 的所有内容:p
标签: javascript typescript promise sequelize.js