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?

Corbin
10.6k2 gold badges30 silver badges51 bronze badges
asked Aug 22, 2014 at 14:16
\$\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
answered Aug 27, 2014 at 11:42
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.