javascript中的链许诺 [英] chain promises in javascript
问题描述
为了在数据库中创建对象,我已经创建了许多类似的承诺.
I've created many promises like that, in order to create object in my database.
var createUserPromise = new Promise(
function(resolve, reject) {
User.create({
email: 'toto@toto.com'
}, function() {
console.log("User populated"); // callback called when user is created
resolve();
});
}
);
最后,我要按我想要的顺序兑现我所有的诺言. (因为somes对象依赖于另一个对象,所以我需要保持顺序)
At the end, I want call all my promises in the order I want. (because somes object depend of other, so I need to keep that order)
createUserPromise
.then(createCommentPromise
.then(createGamePromise
.then(createRoomPromise)));
所以我希望看到:
User populated
Comment populated
Game populated
Room populated
不幸的是,此消息被打乱了,我不知道是什么.
Unfortunately, this messages are shuffled and I don't understand what.
谢谢
推荐答案
看起来像您理解了Promise错误,请重新阅读有关Promise的一些教程,以及此
Looks like you understood promises wrong, re-read some tutorials on promises and this article.
使用new Promise(executor)
创建承诺后,就会立即调用它,因此实际上所有功能都是在创建它们时执行的,而不是在链接它们时执行的.
As soon as you create a promise using new Promise(executor)
, it is invoked right away, so all your function actually are executed as you create them and not when you chain them.
createUser
实际上应该是一个返回promise的函数,而不是promise本身. createComment
,createGame
,createRoom
.
createUser
actually should be a function returning a promise and not a promise itself. createComment
, createGame
, createRoom
too.
然后您就可以像这样将它们链接起来:
Then you will be able to chain them like this:
createUser()
.then(createComment)
.then(createGame)
.then(createRoom)
mongoose返回承诺的最新版本,如果您不传递回调,那么您不会不需要将其包装到一个返回诺言的函数中.
Latest versions of mongoose return promises if you don't pass callbacks, so you don't need to wrap it into a function returning a promise.
这篇关于javascript中的链许诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!