javascript中的链承诺
为了在我的数据库中创建对象,我已经创建了许多这样的承诺javascript中的链承诺,javascript,node.js,mongoose,promise,Javascript,Node.js,Mongoose,Promise,为了在我的数据库中创建对象,我已经创建了许多这样的承诺 var createUserPromise = new Promise( function(resolve, reject) { User.create({ email: 'toto@toto.com' }, function() { console.log("User populated"); // callback called when user is created resol
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();
});
}
);
最后,我要按照我想要的顺序兑现我所有的承诺。(因为有些对象依赖于其他对象,所以我需要保持该顺序)
因此,我希望看到:
User populated
Comment populated
Game populated
Room populated
不幸的是,这些信息被洗牌了,我不明白是什么
谢谢你应该把你的承诺包装成函数。按你的方式,他们马上就被叫来了
var createUserPromise = function() {
return new Promise(
function(resolve, reject) {
User.create({
email: 'toto@toto.com'
}, function() {
console.log("User populated"); // callback called when user is created
resolve();
});
}
);
};
现在,您可以连锁承诺,如下所示:
createUserPromise()
.then(createCommentPromise)
.then(createGamePromise)
.then(createRoomPromise);
createUser()
.then(createComment)
.then(createGame)
.then(createRoom)
看起来你对承诺的理解是错误的,请重新阅读一些关于承诺和此的教程 一旦您使用
新承诺(执行者)
创建承诺,它就会立即被调用,因此所有函数实际上都是在您创建承诺时执行的,而不是在您链接承诺时执行的
createUser
实际上应该是一个返回承诺的函数,而不是承诺本身createComment
,createGame
,createRoom
然后,您将能够像这样链接它们:
createUserPromise()
.then(createCommentPromise)
.then(createGamePromise)
.then(createRoomPromise);
createUser()
.then(createComment)
.then(createGame)
.then(createRoom)
最新版本的if-you-not-pass callbacks,因此不需要将其包装到返回承诺的函数中。这不是链接,看看这个你是对的,我做错了。我更改了代码,一切正常。因为这个解释,我接受你的回答。谢谢你只是一个小补丁。。。。您忘记了
createUser
上的括号,因为它是一个函数。注意-mongoose已经返回承诺-您的代码应该有新承诺
正好零次。请参阅stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it和