Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

node.js - chain promises in javascript

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: '[email protected]'
    }, 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...