Closed Shenrak closed 7 years ago
Two things: about auth, and how to use it.
Because it's asynchronous, the moment you do return result
isn't guaranteed to be after the .then
.
you can do two things here:
async
on the function)
let auth = (email, password) => {
return models.users.filter({
email: email,
password: password,
}).run()
}
await
on the promise (and mark async
)
let auth = async (email, password) => {
return await models.users.filter({
email: email,
password: password,
}).run()
}
The two solutions are equivalent in terms of features, but the async
/await
might be a little bit overkill... You're telling that your function will return a Promise (mark it async
), then you takes out the result of the promise by doing await
on it. So you take the result out of a Promise to put it back in another Promise...
You need to await
on the auth function. Like I said earlier, auth will return a Promise. So if you do console.log(auth(ctx.... ))
, it will log Promise <pending...>
. And the if
will also test on a Promise rather than a value. So you can do the following for example:
module.exports.auth = async function (ctx) {
const user = await auth(ctx.request.body.email, ctx.request.body.password);
console.log(user)
if (user) {
ctx.status = 200
} else {
ctx.set('Content-Type', 'text/plain')
ctx.status = 401
ctx.body = 'Wrong Login or Password'
}
return true
}
Here, contrarly to the precedent case (the auth function), async
/await
help for the clarification of the code greatly.
In fact, the first function, you should use const
instead of let
, and if you take the path of the Promise (I highly recommend it), you can write the function in a simpler way:
const auth = (email, password) =>
models.users.filter({
email: email,
password: password,
}).run()
Btw, about that part
} else {
ctx.set('Content-Type', 'text/plain')
ctx.status = 401
ctx.body = 'Wrong Login or Password'
}
You should here use the new HttpError
class:
throw new HttpError('Wrong Login or Password', 401)
You really should write tutorials mate.
How exactly should I get the result ?
I know it's asynchronous so actually I'm wondering how i should get chat's in the .then(user) callback