简体   繁体   中英

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

EDIT : Here is the actual code that is showing issues

function createEmailView(req, res) {
  validate(req.body, emailCreationSchema)
  .then(validatedBody =>
    db.Email.create({ email: validatedBody.email, userLogin: req.user.login }))
  .then(email => validate(email, emailSchema, { stripUnknown: true }))
  .then((validatedEmail) => { console.log(validatedEmail); return validatedEmail; })
  .then((validatedEmail) => {
    res.status(201).json(validatedEmail);
  })
  .catch((error) => {
    if (error instanceof Sequelize.ValidationError || error.isJoi) {
      res.status(400).json(makeStandardErrorOfValidationError(error));
    } else {
      res.status(500).json(error);
    }
  });
}

If I try printing the "email" on the 3rd line, it is not a plain object but a promise resolving into one. Therefore the validation doesn't work and just strips everything off...

Well, sorry about this but in the end I just mistook a Sequelize Model instance for a Promise. I didn't have a promise given in parameters, therefore everything was good I just had to take the plain object from that instance

email.nodeValues

Thanks to everyone who helped

How about this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM