S
S
Sergey2019-09-10 23:59:46
JavaScript
Sergey, 2019-09-10 23:59:46

How to write an asynchronous function?

Good afternoon. Below is the code that sends a record from the database via get. Moved the function outside the route, but then the question arose, res.send(data) will not wait for getUsers to complete, which is logical. Tell me the best option for performing actions: get data, send a response, without creating an async function inside the route, where there will be two awaits. I wanted to simplify the recording, and use this function repeatedly.

async function getUsers(){
    const db = await pool.connect()
    const data = await db.query('SELECT * FROM users')
    console.log(data.rows)
    
    return data.rows  
}

app.get('/getUsers', (req,res)=>{

   const data = getUsers()
   res.send(data)   
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2019-09-11
@Banjamin

Came up with this option:

async function getUsers(cb){
    const db = await pool.connect()
    const data = await db.query('SELECT * FROM users')
    console.log(data.rows)
    await cb.send(data.rows)
   
}


app.get('/getUsers', (req,res)=>{

   getUsers(res)
     
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question