JavaScript-转换功能至少具有两个回调样式以承诺样式

发布于 2025-01-20 01:32:18 字数 3712 浏览 3 评论 0原文

我从回调风格转向承诺风格,以避免回调使我难以维护代码。我使用 util 模块通过 util.promisify() 导入和转换回调函数,但问题是该函数是否至少有两个回调。函数如何以承诺形式返回,那么我如何管理代码以从两个条件回调中获取承诺。

回调样式示例。

loginAccount = async ({email,password},success,unsuccess) => {
    this.db.query(`SELECT id, password FROM account WHERE email = ?`,[email],(err,result)=>{
      if (err) throw err
      if (result.length === 0) {
        unsuccess("ไม่มีบัญชีนี้อยู่ในระบบ ตรวจสอบอีเมลว่าถูกต้องหรือไม่")
        return
      }
      const account = result[0]
      bcrypt.compare(password,account.password,(error,response)=>{
        if (err) throw err
        if (!(response)) {
          unsuccess("รหัสผ่านไม่ถูกต้อง")
          return
        }
        this.getUser(account.id,success,unsuccess)
      })
    })
  }

我可以像这样转换成承诺形式,但我不知道如何返回成功或不成功。

  loginAccount = async ({email,password},success,unsuccess) => {
    const result = await this.query(`SELECT id, password FROM account WHERE email = ?`,email)
    if (result.length > 0) {
      const account = result[0]
      const response = await this.compareHash(password,account.password)
      if (response) {
        return this.getUser(account.id)
      }
      else {
        // return unsuccess
        // Wrong password
      }
    }
    else {
      // return unsuccess
      // No account in the database
    }
}



回调风格和承诺风格的另一个例子。

registerAccount = async ({firstname,lastname,email,password},success,unsuccess) => {
    this.hasAccount(email,(exist)=>{
      if (exist === true) {
        unsuccess("บัญชีนี้เคยลงทะเบียนไว้แล้ว")
        return
      }
      bcrypt.hash(password,this.saltRound,(err,hash)=>{
        if (err) throw err
        this.db.query(`INSERT INTO account (firstname,lastname,email,password) VALUES(?,?,?,?); 
                      SET @user_id = LAST_INSERT_ID(); INSERT IGNORE INTO role (id) VALUES (@user_id);
                      INSERT INTO student_data (id) VALUES (@user_id); 
                      INSERT INTO profile_image (id) VALUES (@user_id);`,
        [firstname,lastname,email,hash],
        (err,result)=>{
          if (err) throw err
          success()
        })
      })
    })
  }
registerAccount = async ({firstname,lastname,email,password},success,unsuccess) => {
    const exist = await this.hasAccount(email)
    if (exist) {
      // unsuccess function return
      // account is already exists.
      return
    }
    const hash = await this.generateHash(password,this.saltRound)
    const registerQuery = `INSERT INTO account (firstname,lastname,email,password) VALUES(?,?,?,?); 
                          SET @user_id = LAST_INSERT_ID(); INSERT IGNORE INTO role (id) VALUES (@user_id);
                          INSERT INTO student_data (id) VALUES (@user_id); 
                          INSERT INTO profile_image (id) VALUES (@user_id);`
    const result = await this.query(registerQuery,[firstname,lastname,email,hash])
    
    // success function
  }

this.querythis.compareHashthis.generateHash,我正在使用名为 util.promisify() 的库 code> 获取 Promise 函数。

this.query 来自 mysql 查询函数,this.compareHashthis.generateHash 均来自 >bcrypt.comparebrcypt.hash

this.compareHash 将使用明文密码和哈希密码来比较哈希值。

this.generataHash 将使用纯密码和盐轮生成哈希值以返回哈希密码。

this.getUser 函数。

  getUser = async (id) => {
    const result = await this.query(`SELECT * FROM profile_view WHERE id = ?`,id)
    return result[0]
  }

I moving from callback style to promise style to avoid the callback that made me hard to maintain the code. I use util module to import and convert the callback function with util.promisify(), but the question is if the function have at least two callbacks. How the function will return in promise form, then how can I manage the code to get the promise from two conditional callback.

Callback style example.

loginAccount = async ({email,password},success,unsuccess) => {
    this.db.query(`SELECT id, password FROM account WHERE email = ?`,[email],(err,result)=>{
      if (err) throw err
      if (result.length === 0) {
        unsuccess("ไม่มีบัญชีนี้อยู่ในระบบ ตรวจสอบอีเมลว่าถูกต้องหรือไม่")
        return
      }
      const account = result[0]
      bcrypt.compare(password,account.password,(error,response)=>{
        if (err) throw err
        if (!(response)) {
          unsuccess("รหัสผ่านไม่ถูกต้อง")
          return
        }
        this.getUser(account.id,success,unsuccess)
      })
    })
  }

I can convert into promise form like this, but I don't know how to return success or unsuccess.

  loginAccount = async ({email,password},success,unsuccess) => {
    const result = await this.query(`SELECT id, password FROM account WHERE email = ?`,email)
    if (result.length > 0) {
      const account = result[0]
      const response = await this.compareHash(password,account.password)
      if (response) {
        return this.getUser(account.id)
      }
      else {
        // return unsuccess
        // Wrong password
      }
    }
    else {
      // return unsuccess
      // No account in the database
    }
}



another example of callback style and promise style.

registerAccount = async ({firstname,lastname,email,password},success,unsuccess) => {
    this.hasAccount(email,(exist)=>{
      if (exist === true) {
        unsuccess("บัญชีนี้เคยลงทะเบียนไว้แล้ว")
        return
      }
      bcrypt.hash(password,this.saltRound,(err,hash)=>{
        if (err) throw err
        this.db.query(`INSERT INTO account (firstname,lastname,email,password) VALUES(?,?,?,?); 
                      SET @user_id = LAST_INSERT_ID(); INSERT IGNORE INTO role (id) VALUES (@user_id);
                      INSERT INTO student_data (id) VALUES (@user_id); 
                      INSERT INTO profile_image (id) VALUES (@user_id);`,
        [firstname,lastname,email,hash],
        (err,result)=>{
          if (err) throw err
          success()
        })
      })
    })
  }
registerAccount = async ({firstname,lastname,email,password},success,unsuccess) => {
    const exist = await this.hasAccount(email)
    if (exist) {
      // unsuccess function return
      // account is already exists.
      return
    }
    const hash = await this.generateHash(password,this.saltRound)
    const registerQuery = `INSERT INTO account (firstname,lastname,email,password) VALUES(?,?,?,?); 
                          SET @user_id = LAST_INSERT_ID(); INSERT IGNORE INTO role (id) VALUES (@user_id);
                          INSERT INTO student_data (id) VALUES (@user_id); 
                          INSERT INTO profile_image (id) VALUES (@user_id);`
    const result = await this.query(registerQuery,[firstname,lastname,email,hash])
    
    // success function
  }

this.query, this.compareHash and this.generateHash, I'm using the library called util.promisify() to get promise function.

this.query come from mysql query function, this.compareHash and this.generateHash both are come from bcrypt.compare and brcypt.hash

this.compareHash will compare the hash by using plain password and hash password.

this.generataHash will generate the hash by using plain password and salt round to return a hash password.

this.getUser function.

  getUser = async (id) => {
    const result = await this.query(`SELECT * FROM profile_view WHERE id = ?`,id)
    return result[0]
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文