链承诺在JavaScript

我创build了许多这样的承诺,以便在我的数据库中创build对象。

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(); }); } ); 

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

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

所以我期望看到:

 User populated Comment populated Game populated Room populated 

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

谢谢

看起来你明白了承诺错误,重新阅读有关承诺和本文的一些教程。

只要你使用new Promise(executor)创build一个promise,它就立即被调用,所以你的所有函数实际上是在你创build它们时执行的,而不是在你链接它们时执行的。

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

那么你将能够像这样链接他们:

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

最新版本的mongoose返回承诺,如果你不传递callback,所以你不需要把它包装成函数返回一个承诺。

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

 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(); }); } ); }; 

现在你可以链接Promises,像这样:

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