簡體   English   中英

控制台錯誤:await 僅在異步函數和模塊的頂層主體中有效

[英]Console Error: await is only valid in async functions and the top level bodies of modules

我正在nodejs中創建登錄功能,我想通過散列將密碼存儲在mysql db中:我正在使用bcrypt庫。

bcrypt.hash(password, 10, function(err, hash) {
            console.log(hash);
});

上面的代碼對我來說很好,但是如果我想像下面這樣使用 await

let hashedPassword = await bcrypt.hash(password,10);

它顯示以下錯誤為

let hashedPassword = await bcrypt.hash(password,10);
                           ^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules

注意:我的目標是以異步方式使用它,所以使用 await。 懷疑是,

  1. 是第一個異步工作
  2. 第二個是我從視頻中得到的,那是有效的,但在我的情況下它不是,所以這里的問題是什么

以下是詳細信息的總控制器代碼:

const db = require("../connection");

const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

exports.register = (req,res) => {
    const {name, email, password, cpassword} = req.body;

    db.query('SELECT * FROM users WHERE email=?', [email],(error,result)=>{

         if(error){
             console.log(error);
         } else if(result.length > 0){
             return res.render('signup',{
                 message:'Email already exists!'
             })
         } else if(password !== cpassword){
             return res.render('signup',{
                 message: 'Passwords do not match!!'
             });
         }

        let hashedPassword = await bcrypt.hash(password,10);
        console.log(hashedPassword);


        // bcrypt.hash(password, 10, function(err, hash) {
        //     console.log(hash);
        // });
        
    });
}

您的注冊功能不是異步的。 嘗試這個:

exports.register = async (req,res) => {
    ...rest of the code
}

在異步函數中您必須了解的基本知識是使函數異步然后使用等待,但是您的代碼沒有異步函數會引發錯誤。 因此,您必須將父函數設為異步類型。 下面更新了代碼

#previous code..
  db.query('SELECT * FROM users WHERE email=?', [email], async (error,result)=>{
    #other codes here..
    let hashedPassword = await bcrypt.hash(password,10);
    console.log(hashedPassword);
  });

#next code..

這樣你就可以使用哈希和鹽的兩種方式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM