【发布时间】:2015-06-29 18:44:05
【问题描述】:
我试图在承诺的步骤之间传递中间值,但我找不到这样做的干净方法。作为一个用例,这似乎很常见,所以我希望我只是错过了一个模式,而不是完全偏离轨道。
我将 Bluebird 用于 Promise,并使用 Sequelize (SQL ORM)。
示例代码:
db.sync().then(function () {
// When DB ready, insert some posts
return [
BlogPost.create(),
BlogPost.create()
];
}).spread(function (post1, post2) {
// Once posts inserted, add some comments
return [
post1.createComment({ content: 'Hi - on post 1' }),
post2.createComment({ content: 'Hi - on post 2' })
];
}).spread(function (post1, post2) { // THE PROBLEM: Want posts here, not comments
// Do more with posts after comments added, e.g. add tags to the posts
// Can't do that in the above as something needs to wait for
// comment creation to succeed successfully somewhere.
// Want to wait on Comments promise, but keep using Posts promise result
});
到目前为止我最好的解决方案是:
db.sync().then(function () {
// When DB ready, insert some posts
return [
BlogPost.create(),
BlogPost.create()
];
}).spread(function (post1, post2) {
// Once posts inserted, add some comments
return Promise.all([
post1.createComment({ content: 'Hi - on post 1' }),
post2.createComment({ content: 'Hi - on post 2' })
]).then(function () {
// Extra nested promise resolution to pull in the previous results
return [post1, post2];
});
}).spread(function (post1, post2) {
// Do things with both posts
});
当然有更好的方法吗? Bluebird 有 .tap(),它非常接近,但不做 spread() 部分,我找不到一个简单的方法来组合。
【问题讨论】:
标签: javascript promise sequelize.js bluebird