I'm trying to pass through intermediate values between steps in a promise, and I can't find a clean way to do so. This seems pretty common as a use case, so I'm hoping I'm just missing a pattern, rather than being totally off track.
I'm using Bluebird for promises, with Sequelize (SQL ORM).
Example code:
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
});
The best solution I have so far is:
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
});
Surely there's a better way though? Bluebird has .tap(), which is pretty close, but doesn't do the spread() part, and I can't find an easy way to combine then.