Benny Chan
Benny Chan

Reputation: 343

Azure Function connecting SQL server with blank page in browser

I am new to Azure Function and nodejs.

I have a very simple azure function which connects to SQL server by using Azure Function with nodejs. I use the package named "tedious" to connection to SQL server which hosted in Azure. The connection works fine as I can see the result in my Terminal panel in Visual Studio Code by using "context.log" when put the URL "http://localhost:7071/api/Company" into my browser. However, i see nothing in my browser.

I suspect that the "return" called before the function "queryDatabase" is completed but i have no clue how to do this. Any advice?

var Connection = require('tedious').Connection;  
var Request = require('tedious').Request;
var rows = [];
var config = {  
    userName: 'xxx',  
    password: 'xxx',  
    server: 'xxx',  
    options: {encrypt: true, database: 'xxx'}  
};  

var res = {};

module.exports = async function (context, req) {

    context.log('JavaScript HTTP trigger function processed a request.');
    var str = "";
    var connection = new Connection(config); 
    var querystatus = ""; 
    connection.on('connect', function(err) {  
        if(err) {
            context.log(err);
            //context.res = {body : err};
        } else {
            context.log("************Connected*****************");
            //context.res = {body : "Hello!"};  
            queryDatabase(connection);

            // context.res = {
            //     body: "Connected"
            // };
            //context.done();
        }
    });  
    context.log("************BEFORE context.res*****************");
    return {
        body:rows.toString()
    };


    function queryDatabase(connection) { 

        context.log("queryDatabase....started!"); 

        var request = new Request(
            "SELECT [id],[CompanyName] ,[CreatedDate]  FROM [dbo].[Company]",
            function(err, rowCount, rows)
            {
                context.log(rowCount + ' row(s) returned');   
                //context.log("Final Result:" + str);     
            }
        );        

        request.on('row', function(columns) {
            var row = {};
            columns.forEach(function(column) {
                context.log("%s\t%s", column.metadata.colName, column.value);
                row[column.metadata.colName] = column.value;
            });
            rows.push(row);
        });
        connection.execSql(request);

    }

};

Upvotes: 2

Views: 510

Answers (1)

Benny Chan
Benny Chan

Reputation: 343

Finally, I remove the "async " and add a context.done after the result is returned from sql server.

Upvotes: 1

Related Questions