【问题标题】:chain promises in javascriptjavascript中的链承诺
【发布时间】:2016-04-14 07:05:57
【问题描述】:

为了在我的数据库中创建对象,我已经创建了许多这样的 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
      resolve();
    });
  }
); 

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

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

所以我希望看到:

User populated
Comment populated
Game populated
Room populated

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

谢谢

【问题讨论】:

  • 注意 - 猫鼬已经返回承诺 - 你的代码应该有 new Promise 正好零次。请参阅 stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it 和 mongoosejs.com/docs/promises.html

标签: javascript node.js mongoose promise


【解决方案1】:

你应该将你的 Promises 包装到函数中。按照你的方式,它们会立即被调用。

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

现在你可以像这样链接 Promise:

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

【讨论】:

【解决方案2】:

看来你对 Promise 的理解有误,请重新阅读一些关于 Promise 的教程和这个 article

一旦您使用new Promise(executor) 创建了一个promise,它就会立即被调用,因此您的所有函数实际上都是在您创建它们时执行的,而不是在链接它们时执行的。

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

然后你就可以像这样链接它们了:

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

mongoose return promises 的最新版本,如果您不传递回调,则无需将其包装到返回承诺的函数中。

【讨论】:

  • 你是对的,我做错了。我更改了代码,一切正常。由于解释,我接受你的回答。谢谢你
  • 稍微修正一下....你忘了createUser上的括号,因为它是一个函数。
猜你喜欢
  • 1970-01-01
  • 2017-03-13
  • 1970-01-01
  • 2023-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
  • 1970-01-01
相关资源
最近更新 更多