Tuesday 16 May 2017

ES6 nested promises

I'm using promises and I am stuck with an issue, that is more a question of Best Practice.

I have a function that returns a promises resolving into an object (validated object) :

validate(req.body, bodyValidationSchema)

I have another function, creating an object in the database from the validated data and returning a promise resolving into the created object :

db.model.create(validated_data, other_parameters)

However, I can't just chain those functions using them such as :

validate(req.body, bodyValidationSchema)
.then(validated_data => db.model.create(validated_data, other_parameters))
.then(console.log)

Because, the last line will not print the created_object but a Promise resolving into the created object. Therefore I have to do something like this, nesting the promises :

validate(req.body, bodyValidationSchema)
.then(validated_data =>
  db.model.create(validated_data, other_parameters)
  .then(console.log)
)

Is there any better way to do that ? Also, if I replace the console.log by an async task and add another ".then()" not after that task but after the bigger one, it will not wait for that last task (I don't know if that is very clear...)

Thank you very much, Giltho



via Giltho

No comments:

Post a Comment