Home > Enterprise >  filled array is empty when send back to user
filled array is empty when send back to user

Time:11-01

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 [TeledienstMenen_db_Merged].[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)
})

CodePudding user response:

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));

CodePudding user response:

I solved it with adding this:

    request.on('requestCompleted', () => {
        res.send(result)
    })
  • Related