skip to Main Content

I’m trying to get some information from a database in phpmyadmin using sequelize, but when I try to return the values I get "undefined". If I try to console.log the data, it appears just fine. I don’t really understand what the problem is.

UPDATE: I’ve tried using await getTweetInfo(), but I get an error saying that "await is only valid in async function". I need the string that this query should return for another function.


async function getTweetInfo(){
    const data = await sequelize.query('SELECT contenido FROM tweets WHERE id = ?',
    {replacements: [2], type:sequelize.QueryTypes.SELECT})
    return data
}

getTweetInfo()

3

Answers


  1. async function getTweetInfo(){
        const data = await sequelize.query('SELECT contenido FROM tweets WHERE id = ?',
        {replacements: [2], type:sequelize.QueryTypes.SELECT})
        return data
    }
    
    console.log(await getTweetInfo());
    

    [UPDATE]
    I thought it was obvious but let me give a few considerations.

    1. function getTweetInfo returns a Promise which will get resolved once data is returned from database
    2. thus, when calling that function with an intent to consume the data, one should use await

    example i gave is awaiting the result of the function and showing it in console.log()

    Login or Signup to reply.
  2. getTweetInfo returns a Promise.

    Try:

    getTweetInfo().then(data => console.log(data))
    

    Or use await

    await getTweetInfo()
    
    Login or Signup to reply.
  3. The reason why you got the result is that you put the console.log(data) after await. It will wait the query until it finishes and then next to your console.log(data). That’s why you got the result.

    async function getTweetInfo(){
        return sequelize.query('SELECT contenido FROM tweets WHERE id = ?',
        {replacements: [2], type:sequelize.QueryTypes.SELECT})
    }
    
    var data = await getTweetInfo()
    console.log(data)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search