简体   繁体   中英

With async the bcrypt.hash function returns undefined but it works fine with .then

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:

Async methods that accept a callback, return a Promise when callback is not specified if Promise support is available

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM