以下问题由mssql,Nodejs,Gulp,Express和SQL Server Express组成。我能够成功登录到SQL Server Express。但是,当我使用不带callback的bookRoute.js代码片段时,返回值是不确定的。但是,当我使用回调时,我得到了数据。但是,我不明白为什么。
app.js代码段:
var config = {
user: 'user',
password: 'password',
server: 'localhost',
database: 'Books',
options: {
instance: 'SQLEXPRESS'
}
};
sql.connect(config, function(err){
console.log(err);
});
没有回调的bookRoute.js代码段:
bookRouter.route('/')
.get(function (req, res) {
console.log('book router');
var request = new sql.Request();
request.query('select * from books').then(
function (err, recordset) {
console.log(recordset);
})
.catch(function(err){ console.log(err)});
});
带有回调的bookRoute.js代码段:
bookRouter.route('/')
.get(function (req, res) {
console.log('book router');
var request = new sql.Request();
request.query('select * from books',
function (err, recordset) {
console.log(recordset);
});
});
用户访问网页后,控制台应显示结果。不幸的是,不使用回调时,显示的唯一结果是不确定的。
控制台输出:
P:\ub\lic\library>gulp serve
[11:08:28] Using gulpfile P:\ub\lic\library\gulpfile.js
[11:08:28] Starting 'style'...
[11:08:28] Starting 'inject'...
[11:08:53] Finished 'inject' after 808 ms
[11:08:53] Finished 'style' after 25 s
[11:08:53] Starting 'serve'...
[11:08:53] Finished 'serve' after 5.31 ms
[11:08:53] [nodemon] 1.9.2
[11:08:53] [nodemon] to restart at any time, enter `rs`
[11:08:53] [nodemon] watching: *.js src/**/*.js
[11:08:53] [nodemon] starting `node app.js`
running server on port 3000
null
book router
undefined
[11:09:21] [nodemon] restarting due to changes...
Restarting the server.....beep boop beep beep
[11:09:21] [nodemon] restarting due to changes...
Restarting the server.....beep boop beep beep
[11:09:21] [nodemon] starting `node app.js`
running server on port 3000
null
book router
[ { id: 1,
title: 'A,B,C with Big Bird ',
author: 'Michael Jacob ' },
{ id: 2,
title: 'Peter and his Petunias ',
author: 'Jess Holiday ' },
{ id: 3,
title: 'The Amazing Average Guy ',
author: 'Don Dillon ' } ]
没有回调的bookRoute.js代码段:
bookRouter.route('/').get(function (req, res) {
console.log('book router');
var request = new sql.Request();
request.query('select * from books')
.then(function (recordset) {
console.log(recordset);
})
.catch(function (err) {
console.log(err);
});
});
当使用不带回调的bookRoute.js代码片段时,该then
函数应仅包含一个参数,该参数是查询的结果,即文档中所述的方式。出现错误时,catch
将调用该函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句