skip to Main Content

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


  1. Only async the inner function

    Does this work?

    static sendOtp(phone_number) {  // <------------   REMOVED `ASYNC` HERE
            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(async function (response) { // <-------------- ADDED `ASYNC` HERE
                
                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';
            });
    
        }
    
    
    Login or Signup to reply.
  2. You can handle promise in 2 ways, using then or await.
    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 attach async before function name when defining to use await.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search