简体   繁体   English

Javascript function 更改变量值

[英]Javascript function change variable value

I am currently developing signup page and I want to check if email address is already exist in the database.我目前正在开发注册页面,我想检查数据库中是否已经存在 email 地址。

var emailnum = email_num(`select * from contactinfo where email='${email}'`);
        console.log(emailnum); //the output presents Promise { <pending> } not a num.

function sqlExecute(q) {
    return new Promise((resolve, reject) => {
            db.pool.query(q, function(err, result) {
                if (err) {
                    console.log("ERROR ON " + q+"\n");
                    reject(err)
                }
                console.log("SUCCESS ON " + q);
                resolve(result);
            })
        })
        .catch(err => {
            console.log(err);
        })
}

//run check sql
async function email_num(tempquery){
   var result = await sqlExecute(tempquery);
   return result.rowCount;
}

I tried multiple ways but still could not figure it out.我尝试了多种方法,但仍然无法弄清楚。 I would appreciate any help TT我将不胜感激任何帮助 TT

when I console.log, output is Always Promise { }.当我 console.log 时,output 总是 Promise { }。 I tried我试过了

var emailnum = email_num(`select count(*) as count from contactinfo where email='${email}'`)
.then((val)=>{
return val
};
console.log("number"+ emailnum);

The problem here is that you're not allowing the promise to resolve before attempting to retrieve the row count.这里的问题是,在尝试检索行数之前,您不允许 promise 解决。 When you create a function using async the return result is always going to be a promise.当您使用async创建 function 时,返回结果始终是 promise。 Here are a few solutions that will get you your desired result:这里有一些解决方案可以让您获得想要的结果:

Solution 1: Use console.log to print the result of the promise after it has been resolved.解决方案1:使用console.log打印promise解决后的结果。

const email = 'something@gmail.com'
const numOfEmailsQuery = `SELECT * FROM contactinfo WHERE email = '${email}'`

email_num(numOfEmailsQuery)
  .then(console.log)
  .catch(console.error)

Solution 2: Use await inside of an async function to resolve the result of the promise and store it in a variable.解决方案 2:在async function 中使用await来解析 promise 的结果并将其存储在变量中。 Then print the result using console.log然后使用console.log打印结果

async function printNumberOfEmails(email) {
  const numOfEmailsQuery = `SELECT * FROM contactinfo WHERE email = '${email}'`
  try {
    const numOfEmails = await email_num(numOfEmailsQuery)
    console.log(numOfEmails)
  } catch (err) {
    console.error(err)
  }
}

const email = 'something@gmail.com'
printNumberOfEmails(email)

Hope that helps!希望有帮助! Good luck!祝你好运!

First off, it's good practice to use prepared statements instead.首先,最好使用准备好的语句。

Also, you should just care about the count, so instead of select * , do select count(*) as count .此外,您应该只关心计数,因此不要select * ,而是将select count(*) as count Then you'll need check either the number of rows that result returned or the first index of rows, then the count property of that.然后你需要检查result返回的行数或行的第一个索引,然后是它的count属性。

It should look something like this它应该看起来像这样

function fetchEmailExists(email) {
    const statement = 'select count(*) as count from contactinfo where email = $1';
    return new Promise((resolve, reject) => {
            db.pool.query(statement, [ email ], function(error, result) {
                if (!error && result.rows.length > 0) {
                    resolve(result.rows[0]['count'] > 0);
                } else {
                    reject(error);
                }
            });
        })
        .catch(error => {
            console.log(error);
        });
}

// Here is your call to fetchEmailExists
fetchEmailExists('test123@example.com')
  .then(boolean => console.log(boolean));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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