开发者问题收集

NodeJS 函数中的 then/catch 似乎捕获了函数外的代码

2017-07-28
3502

我正在尝试构造此代码,以便可以从多个地方调用 getStudent。我正在尝试编写一些 JSON 例程。我尝试了 err first 回调模式。困扰我的不是错误本身,而是错误被 getStudent 内部的一个捕获捕获。

顺便说一句,我发现错误是执行 status(200) 而不是 status(0)。

我应该如何重构这些捕获,以便它们不会影响主代码?或者我完全误用了回调概念?似乎“then/catch”是使用 mssql 处理异步的正确方法。

var express = require('express');
var app = express();

// config for your database
var config = {
    user: 'ReadOnlyUser1',
    password: 'whatever',
    server: 'localhost\\SQLEXPRESS', 
    database: 'StudentsOld' 
};

var lookupStudentId = 31; 


const sql = require('mssql');

var connPool = new sql.ConnectionPool(config);

function getStudent(studentId, callback) {
        console.log("Starting getStudent"); 
        nullResult = {}; 
        connPool.connect().
        then (function() {
            console.log('Connected - starting query'); 
            var request = new sql.Request(connPool); 
            var sqlQuery = 'select student_firstname, student_lastname from students where student_id = ' + studentId;  
            request.query(sqlQuery).
            then(function (recordSet) {
                    console.log('Query completed'); 
                    connPool.close(); 
                    console.log("recordSet="); 
                    console.dir(recordSet); 
                    callback(nullResult, recordSet); 
            }).catch(function (queryErr) {
                    console.log('Error in database query: ' + queryErr); 
                    callback('Error in db query: ' + queryErr, nullResult);  
                });
        }).catch(function (connErr) { 
                    console.log('Error in database connection: ' + connErr); 
                    callback('Error in db conn: ' + connErr, nullResult);  
                }); 
        console.log('fall thru 1'); 
}

function isEmptyObject(obj) {
  return !Object.keys(obj).length;
}

app.get('/student', function(request, response){
    console.log('Neal Test1'); 
    getStudent(lookupStudentId, function(err, result){
        console.log('Back from getStudent'); 
        if(!isEmptyObject(err)) {
            console.log("error400=" + err); 
            console.log("empty test=" + Object.keys(err).length); 
            response.status(400).send(err);
        }
        else 
        {
            console.log("result="); 
            console.dir(result); 
            console.log('about to send back status=0'); 
            response.status(0).send(result); 
        }
    })
    return;
});

app.listen(3000, function () {
    console.log('Express server is listening on port 3000');
});

我在浏览器中输入: http://localhost:3000/student 来运行上述代码。

控制台输出为:

C:\Software\nodejs\myapp>node index.js
Express server is listening on port 3000
Neal Test1
Starting getStudent
fall thru 1
Connected - starting query
Query completed
recordSet=
{ recordsets: [ [ [Object] ] ],
  recordset:
   [ { student_firstname: 'Jonah                  ',
       student_lastname: 'Hill                    ' } ],
  output: {},
  rowsAffected: [ 1 ] }
Back from getStudent
result=
{ recordsets: [ [ [Object] ] ],
  recordset:
   [ { student_firstname: 'Jonah                  ',
       student_lastname: 'Hill                    ' } ],
  output: {},
  rowsAffected: [ 1 ] }
about to send back status=0
Error in database query: RangeError: Invalid status code: 0
Back from getStudent
error400=Error in db query: RangeError: Invalid status code: 0
empty test=53

修订 1:

function getStudent(studentId) {
        console.log("Starting getStudent"); 
        recordset = {}; 
        connPool.connect().
        then (function() {
            console.log('Connected - starting query'); 
            var request = new sql.Request(connPool); 
            var sqlQuery = 'select student_firstname, student_lastname from students where student_id = ' + studentId;  
            request.query(sqlQuery).
            then(function (recordSet) {
                    console.log('Query completed'); 
                    connPool.close(); 
                    console.log("recordSet="); 
                    console.dir(recordSet); 
                    return recordset; 
            }).catch(function (queryErr) {
                    console.log('Error in database query: ' + queryErr); 
                    return queryErr; 
                });
        }).catch(function (connErr) { 
                    console.log('Error in database connection: ' + connErr); 
                    return connErr; 
                }); 
        console.log('fall thru 1'); 
}


app.get('/student', function(request, response){
    console.log('Neal Test1 - start app.get for /student'); 
    getStudent(lookupStudentId)
        .then (function(recordset)  {
            console.log('Back from getStudent,  recordSet='); 
            console.dir(recordSet); 
            response.status(200).send(recordset); 
        })
        .catch (function(err) {
            console.log("error400=" + err); 
            console.log("empty test=" + Object.keys(err).length); 
            response.status(400).send(err);
        })
    return;
});

修订 1 的结果:

Express server is listening on port 3000
Neal Test1 - start app.get for /student
Starting getStudent
fall thru 1
TypeError: Cannot read property 'then' of undefined
    at C:\Software\nodejs\wisdomcalls\index.js:55:9
    at Layer.handle [as handle_request] (C:\Software\nodejs\wisdomcalls\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Software\nodejs\wisdomcalls\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Software\nodejs\wisdomcalls\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Software\nodejs\wisdomcalls\node_modules\express\lib\router\layer.js:95:5)
    at C:\Software\nodejs\wisdomcalls\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Software\nodejs\wisdomcalls\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Software\nodejs\wisdomcalls\node_modules\express\lib\router\index.js:275:10)
    at expressInit (C:\Software\nodejs\wisdomcalls\node_modules\express\lib\middleware\init.js:40:5)
    at Layer.handle [as handle_request] (C:\Software\nodejs\wisdomcalls\node_modules\express\lib\router\layer.js:95:5)
Connected - starting query
Query completed
recordSet=
{ recordsets: [ [ [Object] ] ],
  recordset:
   [ { student_firstname: 'Jonah                ',
       student_lastname: 'Hill                    ' } ],
  output: {},
  rowsAffected: [ 1 ] }

从日志中,您可以看到主函数在数据库连接之前就已经在运行了。

修订 2: 这似乎返回的是连接而不是查询?请参阅 console.log“undefined”。

function getStudent(studentId) {
        console.log("Starting getStudent"); 
        recordset = {}; 
        return connPool.connect()
        .then (function() {
            console.log('Connected - starting query'); 
            var request = new sql.Request(connPool); 
            var sqlQuery = 'select student_firstname, student_lastname from students where student_id = ' + studentId;  
            return request.query(sqlQuery)
            ;
            /*
            .then(function (recordSet) {
                    console.log('Query completed'); 
                    connPool.close(); 
                    console.log("recordSet="); 
                    console.dir(recordSet); 
                    //return recordset; 
            }).catch(function (queryErr) {
                    console.log('Error in DB query: ' + queryErr); 
                    //return queryErr; 
                });
        }).catch(function (connErr) { 
                    console.log('Error in DB connection: ' + connErr); 
                    //return connErr; 
             */
            }); 
        console.log('fall thru 1'); 
}

结果:

Connected - starting query
SQL Query = select student_firstname, student_lastname from students where student_id = 31
error400=ReferenceError: recordSet is not defined
empty test=0
2个回答

您似乎在混合 Promises 和回调,这让一切都变得更加混乱。promise 的一般模式是返回它们,然后调用 then ,这将为您提供已解析 Promise 的返回值。请记住 then() 也会返回一个 Promise,这就是您如何将它们串联起来。

您只需从函数中返回 connPool.connect() 返回的 Promise。然后被调用者可以对其调用 then()catch() 。错误将上浮至最后的 catch()

我没有 SQL 连接,因此无法测试,但我脑海中浮现的想法是这样的(简化以便清晰):

const sql = require('mssql');

var connPool = new sql.ConnectionPool(config);

function getStudent(studentId) {
        nullResult = {}; 
        return connPool.connect() //return the promise from your function
        .then (function() {
            console.log('Connected - starting query'); 
            var request = new sql.Request(connPool); 
            var sqlQuery = 'select student_firstname, student_lastname from students where student_id = ' + studentId;  
            connPool.close(); 
            return request.query(sqlQuery) // returns the promise from request
        })      

}


app.get('/student', function(request, response){
    getStudent(lookupStudentId)
    .then(function(recordSet){
        // recordSet should be promise resolution of request.query
    })
    .catch(function(err) {
        // catch errors here
    })
})

这是一个配对示例,有助于通过一个简单的异步承诺模拟来展示承诺链的实际操作,该模拟返回您发送的内容。您可以取消注释 throw() 以查看错误如何冒泡:

function getStudent(val) {
        return async(val)
        .then (function(v) {
           // console.log("In outer with, ", v)
            return async("processes value: " + v)
        })
        .then(function (value) {
            //console.log("Inside value got: ", value)
            //throw("Some Error")
            return async("processed again: " + value)
        })
}

getStudent("Start_Value")
.then((value) => {
    console.log("Final return: ",value)
})
.catch((err) => console.log("whoops err: ", err))

function async(p) {
    return new Promise((resolve, reject) => {
        //throw("async error")
        setTimeout(() => {
            resolve( "FROM ASYNC: " + p )
        }, 500)
    })
}
Mark
2017-07-28

您的回调概念没问题,您还可以在 getStudent 函数中创建自己的承诺并返回它,这将使您的代码更具可读性。问题在于 response.status(0).send(result);xhr 调用不存在这样的状态,否则会产生错误。在这里,您可以通过它们的全局可接受用法获得一些有用的状态 http://www.restapitutorial.com/httpstatuscodes.html

vaibhavmaster
2017-07-28