Here is the code with async (returns undefined
)
userService.register = (username, password) => {
return bcrypt.hash(password, saltRounds, async(err, hash) => {
const newUser = new user({
username: username,
password: hash
})
return await newUser.save()
})
}
and this is the same code with .then
, it works correctly
userService.register = (username, password) => {
return bcrypt.hash(password, saltRounds)
.then(hash => {
const newUser = new user({
username: username,
password: hash
})
return newUser.save()
})
}
This is documented behaviour:
You're passing a callback in your first example, so bcrypt
doesn't return a promise.
Another way to write your code is to make the wrapping function async
:
userService.register = async (username, password) => {
const hash = await bcrypt.hash(password, saltRounds);
const newUser = new user({
username: username,
password: hash
})
return await newUser.save(); // or just `return newUser.save()`
}
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.