2
\$\begingroup\$

In my code I have to login a user with username and password. But if the user sends his e-mail instead of his username, I have to resolve it with another request.

This is what the code looks like:

exports.auth = (request, response, next) ->
  username = request.body.username
  if request.body.email
      users.findByEmail request.body.email, (error, result) ->
          return next new InternalServerError(error) if error
          username = result[0].username
          auth.auth username, request.body.password, (error, result) ->
              return next new InternalServerError(error) if error
              response.json responseData
  else
      auth.auth username, request.body.password, (error, result) ->
          return next new InternalServerError(error) if error
          response.json responseData

As you can see there are 3 duplicate lines.

Does anyone know a good code style do make this better? Maybe with Promises? Async Waterfall? Waitfor?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Promises would make sense to me, but first step would be to extract stuff into functions.

You don't really need promises for this, though. Here's one way to just do it with plain callbacks:

exports.auth = (request, response, next) ->
  getUsername = (request, cb) ->
    email = request.body.email
    return cb null, request.body.username unless email

    users.findByEmail email, (error, result) ->
      return cb new InternalServerError(error) if error
      cb null, result[0].username

  getUsername (err, username) ->
    return next err if err
    auth.auth username, request.body.password, (err, json) ->
      return next err if err
      response.json json
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.