【问题标题】:With async the function returns undefined but it works fine with .then使用 async 函数返回 undefined 但它适用于 .then
【发布时间】:2022-06-23 19:41:43
【问题描述】:

这里是异步代码(返回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()
  })
}

这是与.then相同的代码,它可以正常工作

userService.register = (username, password) => {
  return bcrypt.hash(password, saltRounds)
    .then(hash => {
      const newUser = new user({
        username: username,
        password: hash
      })
      return newUser.save()
    })
}

【问题讨论】:

    标签: javascript asynchronous async-await promise bcrypt


    【解决方案1】:

    这是记录在案的行为:

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

    您在第一个示例中传递了一个回调,因此 bcrypt 不会返回一个承诺。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-22
      • 2020-10-02
      • 2022-10-04
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多