2016-01-09 93 views
5

我已经创建了许多类似的承诺,以便在我的数据库中创建对象。在javascript中的链承诺

var createUserPromise = new Promise(
    function(resolve, reject) { 
    User.create({ 
     email: '[email protected]' 
    }, function() { 
     console.log("User populated"); // callback called when user is created 
     resolve(); 
    }); 
    } 
); 

最后,我想按我想要的顺序打电话给我所有的承诺。 (因为萨姆对象依赖其他,所以我需要保持这个顺序)

createUserPromise 
    .then(createCommentPromise 
    .then(createGamePromise 
     .then(createRoomPromise))); 

所以我希望看到:

User populated 
Comment populated 
Game populated 
Room populated 

不幸的是,这个消息被打乱,我不明白。

谢谢

+0

注 - 猫鼬已经返回承诺 - 您的代码应该有“新的承诺”完全零次。请参阅stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it和http://mongoosejs.com/docs/promises.html –

回答

10

看起来你理解错的承诺,重新阅读上的承诺,这article一些教程。

只要您使用new Promise(executor)创建承诺,就立即调用它,这样所有的函数实际上都会在创建时执行,而不是在链接它们时执行。

createUser实际上应该是一个返回承诺而不是承诺本身的函数。 createCommentcreateGamecreateRoom

然后,你就可以把它们连这样的:

createUser() 
.then(createComment) 
.then(createGame) 
.then(createRoom) 

最新的版本mongoose return promises如果不通过回调,这样你就不会需要将其包装成返回承诺的功能。

+0

你是对的,我做错了。我改变了我的代码,一切顺利。由于解释,我接受你的回答。谢谢你 – Epitouille

+1

只是一个小小的修复....你忘了'createUser'的括号,因为它是一个函数。 – juliobetta

+0

@juliobetta好抓! – nvartolomei

3

你应该把你的承诺包装成函数。你正在做的事情,他们马上就会被调用。

var createUserPromise = function() { 
    return new Promise(
    function(resolve, reject) { 
     User.create({ 
     email: '[email protected]' 
     }, function() { 
     console.log("User populated"); // callback called when user is created 
     resolve(); 
     }); 
    } 
); 
}; 

现在你可以链的承诺,像这样:

createUserPromise() 
.then(createCommentPromise) 
.then(createGamePromise) 
.then(createRoomPromise); 
+1

这不是链接,看看这个http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html – nvartolomei

+0

你是对的。更新! – juliobetta