ga-wdi-boston/express-api-template-ARCHIVED

Promise hell

Opened this issue · 3 comments

Remove thens within thens in example controller. Best practice for promises is not nesting thens. The return value from the previous then will be passed to the following one if information needs to be passed on.

For example, update can be:

const update = (req, res, next) => {
  let search = { _id: req.params.id, _owner: req.currentUser._id };
  Example.findOne(search)
    .then(example => {
      if (!example) {
        return next();
      }

      delete req.body._owner;  // disallow owner reassignment.
      return example.update(req.body.example) 
    })
    .then(() => res.sendStatus(200));
    .catch(err => next(err));
};
gaand commented

I believe this refactoring introduces a bug as it may call next and res.sendStatus(200).

Agreed. I'd like to get our of the promise nesting if possible, but this isn't the right way to do it. =/