I am working with Nodejs and using expressjs,Right now i want to get data from datbase(mysql) but i am getting following error
"await is only valid for async function"
How can i resolve this, here is my current code
static async sendOtp(phone_number) {
var otp=Math.floor(1000 + Math.random() * 9999);
var config = {
method: 'get',
maxBodyLength: Infinity,
url: 'http://2factor.in/API/V1/XXXXXXXXXXXXXXXX/SMS/+91XXXXXXXXXX/12345/XXXXXXXX',
headers: { }
};
axios(config)
.then(function (response) {
const sql = "SELECT phoneNumber FROM verifyOtp WHERE phoneNumber = '${phone_number}'";
const [rows, fields] = await pool.execute(sql);
console.log('total rows are '+ rows);
if(rows>0)
{
//further logic 1
}
else
{
//further logic 2
}
})
.catch(function (error) {
return 'error';
});
}
2
Answers
Only
async
the inner functionDoes this work?
You can handle promise in 2 ways, using
then
orawait
.It is a good coding practice to use one of them in the whole codebase identically. I recommend you use
async
,await
structure more so that you can keep code structure clearly. And you need to attachasync
before function name when defining to useawait
.