-1

I try to get data from an azure database with SQL and for this I use tedious. When I execute the code, the array "result" gets filled up with data but when de respond sends the array "result" to the user it is empty. Why and how can I solve it? (I want to send it back in JSON format, the legth is unknown I use 5 to debug).

This is my code

router.get('/', async (req, res) => {
    result = []
    let rowData = {}
    const request = new Request(
        `SELECT TOP (5) [LogID]
        ,[OpdrachtID]
        ,[ChangeLog]
        ,[TimeStamp]
        ,[PersonID]
    FROM [log].[LOpdracht]`,
    function (err, rowCount, rows) {
        if (err) throw err
    })
    connection.execSql(request)

    request.on('row', function(columns){
        rowData = {}
        columns.forEach(function(column){
            rowData[column.metadata.colName] = column.value
        })
        result.push(rowData)
    })

    res.send(result)
})

Bjop
  • 330
  • 4
  • 19
  • 2
    Your `send()` occurs before the *asynchronous* `on('row, callback)` completes – charlietfl Oct 31 '21 at 15:36
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – CherryDT Oct 31 '21 at 15:54

2 Answers2

2

Looks like you are using Tedious. If that is so then you can use the 'done' event to be notified when the request has completed and all rows have been read into result.

request.on('done', () => res.send(result));

Update: As the note in the documentation points out, since you are using execSql you will need to listen to doneProc and doneInProc instead:

request.on('doneProc', () => res.send(result));
request.on('doneInProc', () => res.send(result));
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
  • Yes I use Tedious but this did not work for me I had to use 'requestCompleted'. but thank you for pointing me the right direction. – Bjop Oct 31 '21 at 15:53
0

I solved it by adding this:

    request.on('requestCompleted', () => {
        res.send(result)
    })
Bjop
  • 330
  • 4
  • 19