简体   繁体   中英

azure javascript function returns nothing after callback

I'm trying to execute a MS SQL query in an azure javascript function and return the results using context.res.body. The query is executed fine and I can see the result in the log, but I can't return it in the context.res.body inside my callback. It seems I can't build context.res.body inside my callback. What am I doing wrong?

code:

var Connection = require('tedious').Connection;
var Request = require('tedious').Request
var TYPES = require('tedious').TYPES;

module.exports = async function (context, req) {
    context.log('authenticate request received');

    if (req.body && req.body.email && req.body.password) {

        var myRows = [];

        const config = {
            authentication: {
            options: {
                userName: "myData", // update me
                password: "myData" // update me
            },
            type: "default"
            },
            server: "myData.database.windows.net", // update me
            options: {
            database: "myData", //update me
            encrypt: true
            }
        }
        console.log("connect");

        var connection = new Connection(config);

        connection.on("connect", err => {
            if (err) {
                console.error(err.message);
            } else {
                console.log("Connected");  
                executeStatement(connection, function(error, rows) {
                    if (error) {
                        console.error(error.message);
                    } else {
                        console.log("disconnect")
                        myRows = rows;
                        connection.close();
                    }
                });
            }
        });

        connection.on("end", () => {
            console.log("respond to request");
            console.log(myRows);
            context.res = {
                body: myRows
            };
            context.done();
        })

    }
    else {
        context.res = {
            status: 401,
            body: {
                message: "not okay"
            }
        };
        console.log("not okay");
        context.done();
    }


    /**************** FUNCTIONS ****************/
    function executeStatement(connection, callback) {  
        const rows = [];

        const request = new Request(
            `SELECT ID, NickName, FirstName, Token, Provider FROM dbo.users WHERE Email=` + '\'' + req.body.email + '\'' + ' AND Password=' + '\'' + req.body.password + '\'',
            (err, rowCount) => {
              if (err) {
                console.error(err.message);
              } else {
                console.log('request: ' + `${rowCount} row(s) returned`);
                callback(null, rows);
              }
            }
        );

        request.on('row', function(columns) {  
            var row = {};

            columns.forEach(function(column) {
                if (column.value === null) {  
                    console.log('row: ' + column.metadata.colName + ' NULL');  
              } else {

                    row[column.metadata.colName] = column.value;
                    console.log("row: " + column.metadata.colName + " " + column.value);
              }
            });  

            rows.push(row);
        });

        connection.execSql(request);
    }  

};

log:

connect
row: ID 1
row: NickName test
row: FirstName NULL
row: Token Token
row: Provider johnykes
request: 1 row(s) returned
disconnect
respond to request
[ { ID: 1, NickName: 'test', Token: 'Token', Provider: 'johnykes' } ]

Couple of things to try :

  • executeStatement should be an Asynchronous function and also you should move all the assignment and functionality of Azure Function into the callback expression something like below( Haven't tried with SQL queries but with other it worked, so check the proper parenthesis):

 connection.on("connect", err => { if (err) { console.error(err.message); } else { console.log("Connected"); executeStatement(connection, function(error, rows) { if (error) { console.error(error.message); } else { console.log("disconnect") myRows = rows; connection.close(); } connection.on("end", () => { console.log("respond to request"); console.log(myRows); context.res = { body: myRows }; context.done(); }) } else { context.res = { status: 401, body: { message: "not okay" } }; console.log("not okay"); context.done(); } }); } });

  • Additionally , please add the relevant header while creating response like below:

 context.res = { status: 302, headers: { 'Content-Type': 'application/json' }, body:{} }; context.done();

Please try and let me know if it worked.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM