gpt4 book ai didi

javascript - 如何通过中间阶段传递 promise 结果

转载 作者:行者123 更新时间:2023-11-28 00:09:30 25 4
gpt4 key购买 nike

我正在尝试在 promise 的步骤之间传递中间值,但我找不到一种干净的方法来做到这一点。作为一个用例,这似乎很常见,所以我希望我只是错过了一个模式,而不是完全偏离轨道。

我使用 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() 部分,而且我找不到一种简单的方法来组合。

最佳答案

我关闭了此问题,但随后重新打开,因为您的问题比一般问题要具体得多。 Make sure your read this question and answers关于一般性问题。

对于上面一个操作的特定上下文 - 您可以将 .return 与 bluebird 一起使用来覆盖返回值:

db.sync().then(function () {
...
}).spread(function (post1, post2) {
return Promise.all([
post1.createComment({ content: 'Hi - on post 1' }),
post2.createComment({ content: 'Hi - on post 2' })
]).return([post1, post2]); // use .return here
}).spread(function (post1, post2) { comments
// posts here
});

关于javascript - 如何通过中间阶段传递 promise 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31028357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com