【发布时间】:2016-03-10 10:04:44
【问题描述】:
以下是我正在处理的一个典型的 Promise 函数。
var _delete = function(t, id) {
return Promise.cast(Event.find({where: {id: id}}, {transaction: t}))
.then(function(d){
if (d) {
// ------- (*)
return Promise.cast(d.updateAttributes({status: -1}, {transaction: t}))
.then(function(){
// do inventory stuff
return Promise.cast(Inventory.update({}).exec())
.then(function(d){
// do something
})
}).then(function(){
// do product stuff
return Promise.cast(Product.update({}).exec())
.then(function(d){
// do something
})
})
} else {
return Promise.reject('this transaction list does not exist');
}
});
};
这看起来没问题,直到我处理更复杂的更新/创建代码会变得非常混乱。
目前我正在做的承诺是 1.我有很多无用的return true语句,唯一的目的是去下一个.then语句 2. promise 以嵌套的方式编程。输入参数通常很复杂并且有超过 1 个参数,所以我不能做这样的事情
.then(fun1).then(fun2)
...等
这使我无法通过'tap' .then 语句启用/禁用功能。
所以我的问题是如何正确执行此操作?谢谢..
以下是我所说的真正丑陋的事情......
var _process = function(t, tid) {
var that = this;
return Promise.cast(Usermain.find({where: {transaction_id: tid}}))
.bind({}) // --- (*)
.then(function(d){
this.tmain = d;
return true; // ---- do nothing, just go to next thennable (is this correct)
}).then(function(){
return Promise.cast(Userlist.findAndCountAll({where: {transaction_id: tid}}))
}).then(function(d){
this.tlist = d;
return true; // ---- do nothing, just go to next thennable (is this correct)
}).then(function(){
if (this.tmain.is_processed) {
return Promise.reject('something is wrong');
}
if (this.tlist.count !== this.tmain.num_of_tran) {
return Promise.reject('wrong');
}
return Promise.resolve(JSON.parse(JSON.stringify(this.tlist.rows)))
.map(function(d){
if (d.is_processed) return Promise.reject('something is wrong with tran list');
return true; // goto next then
});
}).then(function(){
return Promise.cast(this.tmain.updateAttributes({is_processed: 1}, {transaction: t}));
}).then(function(){
return Promise.resolve(this.tlist.rows)
.map(function(d){
var tranlist = JSON.parse(JSON.stringify(d));
return Promise.cast(d.updateAttributes({is_processed: 1, date_processed: Date.now()}, {transaction: t}))
.then(function(d){
if (!d) {
return Promise.reject('cannot update tran main somehow');
} else {
if (tranlist.amount < 0) {
return Usermoney._payBalance(t, tranlist.user_id, -tranlist.amount);
} else {
return Usermoney._receiveBalance(t, tranlist.user_id, tranlist.amount);
}
}
});
});
});
}
【问题讨论】:
-
为什么需要那些
JSON.parse(JSON.stringify(…))s? -
我认为当数组对象是 BSON 时 lodash 会做一些意想不到的事情。此外,我使用的 ORM 是 sequelize,我找不到将返回数据类型转换为 JSON 的内在方法。
-
我认为 mongoose 实例有一个
.toJSON方法可以做到这一点(这就是JSON.stringify首先起作用的原因)。 -
有帮助。现在会记住这一点,因为代码仍然完全在 ES5 中..
标签: javascript node.js promise bluebird