javascript中的链式承诺 [英] chain promises in javascript

查看:27
本文介绍了javascript中的链式承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了在我的数据库中创建对象,我创建了许多这样的承诺.

var createUserPromise = new Promise(功能(解决,拒绝){用户创建({电子邮件:'toto@toto.com'}, 功能() {console.log("用户填充");//创建用户时调用的回调解决();});});

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

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

所以我希望看到:

用户填充评论已填充游戏已填充房间有人住

不幸的是,这条消息被洗牌了,我不明白是什么.

谢谢

解决方案

看起来你对 promises 理解有误,重新阅读一些关于 promises 的教程和这个 文章.

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

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

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

createUser().then(createComment).then(创建游戏).then(创建房间)

最新版本的 mongoose return promises 如果您不传递回调,那么您就不会'不需要把它包装成一个返回承诺的函数.

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

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

So I expect to see :

User populated
Comment populated
Game populated
Room populated

Unfortunately, this messages are shuffled and I don't understand what.

Thanks

解决方案

Looks like you understood promises wrong, re-read some tutorials on promises and this article.

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 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)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆