Skip to content
Advertisement

chain promises in javascript

I’ve created many promises like that, in order to create object in my database.

JavaScript

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)

JavaScript

So I expect to see :

JavaScript

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

Thanks

Advertisement

Answer

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement