[英]Node.js mssql return query result to ajax
我是学习Node.js的新手,所以我仍然习惯于异步编程和回调。 我正在尝试将记录插入到MS SQL Server数据库中,并将新行的ID返回给我的视图。
打印到console.log时,mssql查询正常工作。 我的问题是不知道如何正确返回数据。
这是我的mssql查询 - 在addJob.js中:
var config = require('../../db/config');
async function addJob(title) {
var sql = require('mssql');
const pool = new sql.ConnectionPool(config);
var conn = pool;
let sqlResult = '';
let jobID = '';
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query(`INSERT INTO Jobs (Title, ActiveJD) VALUES ('${title}', 0) ; SELECT @@IDENTITY AS JobID`).then(function (result) {
jobID = result['recordset'][0]['JobID'];
conn.close();
//This prints the correct value
console.log('jobID: ' + jobID);
}).catch(function (err) {
console.log('Unable to add job: ' + err);
conn.close();
});
}).catch(function (err) {
console.log('Unable to connect to SQL: ' + err);
});
// This prints a blank
console.log('jobID second test: ' + jobID)
return jobID;
}
module.exports = addJob;
这是我的前端,其中模式框采用字符串并将其传递给上述查询。 我希望它然后接收查询的返回值并重定向到另一个页面。
// ADD NEW JOB
$("#navButton_new").on(ace.click_event, function() {
bootbox.prompt("New Job Title", function(result) {
if (result != null) {
var job = {};
job.title = result;
$.ajax({
type: 'POST',
data: JSON.stringify(job),
contentType: 'application/json',
url: 'jds/addJob',
success: function(data) {
// this just prints that data is an object. Is that because I'm returning a promise? How would I unpack that here?
console.log('in success:' + data);
// I want to use the returned value here for a page redirect
//window.location.href = "jds/edit/?jobID=" + data;
return false;
},
error: function(err){
console.log('Unable to add job: ' + err);
}
});
} else {
}
});
});
最后这里是调用函数的快速路由器代码:
const express = require('express');
//....
const app = express();
//....
app.post('/jds/addJob', function(req, res){
let dataJSON = JSON.stringify(req.body)
let parsedData = JSON.parse(dataJSON);
const addJob = require("../models/jds/addJob");
let statusResult = addJob(parsedData.title);
statusResult.then(result => {
res.send(req.body);
});
});
我一直在阅读承诺并试图找出需要改变的地方,但我没有运气。 有人可以提供任何提示吗?
您需要实际从函数中返回一个值才能生效。 由于嵌套了Promises,你需要在这里返回几个。 承诺的核心功能之一是,如果您返回Promise,它将参与调用Promise链。
因此,请更改以下行
jobID = result['recordset'][0]['JobID'];
至
return result['recordset'][0]['JobID']
和
req.query(`INSERT INTO Jobs (Title, ActiveJD) VALUES ('${title}', 0) ; SELECT @@IDENTITY AS JobID`).then(function (result) {
至
return req.query(`INSERT INTO Jobs (Title, ActiveJD) VALUES ('${title}', 0) ; SELECT @@IDENTITY AS JobID`).then(function (result) {
和
conn.connect().then(function () {
至
return conn.connect().then(function () {
您可能需要在返回后立即移动代码。 你还能得到更好的服务移动conn.close()
到一个单一的.finally
的连接链的末端。
我建议您编写一个可以用来玩游戏的测试,直到你做对了。
const jobId = await addJob(...)
console.log(jobId)
或者,重写代码以使用await而不是.then()调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.