Chain promises in javascript

I created many such promises to create an 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(); }); } ); 

In the end, I want to name all my promises in the order I want. (because somes object depends on another, so I need to keep this order)

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

Therefore, I expect to see:

 User populated Comment populated Game populated Room populated 

Unfortunately, these messages are shuffled, and I do not understand that.

thanks

+5
source share
2 answers

You seem to understand that promises are wrong, re-read a few promises tutorials and this article .

As soon as you create a promise using new Promise(executor) , it is called immediately, so your whole function is executed as soon as you create them, and not when you bind them.

createUser should actually be a function that returns a promise, not the promise itself. createComment , createGame , createRoom too.

Then you can link them like this:

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

The latest versions of mongoose return promises , if you do not go through callbacks, so you do not need to insert them into the function returns a promise.

+10
source

You must wrap your Promises functions in functions. The way you do it, they are immediately called.

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

Now you can bind Promises, for example:

 createUserPromise() .then(createCommentPromise) .then(createGamePromise) .then(createRoomPromise); 
+3
source

Source: https://habr.com/ru/post/1240245/


All Articles