好的,所以我很清楚如何用 C# 编程,而且我最近开始用 JS 编程(node js)。老实说,我对异步调用感到震惊。
假设我在 C# 中有这段代码:
var t_1 = SomeAsyncTask();
var t_2 = SomeOtherAsyncTask();
Task.WaitAll(t_1, t_2);
var res_1 = t_1.Result;
var res_2 = t_2.Result;
有与此等效的 JS 吗?到目前为止,我已经做到了:
In User.js:
var express = require("express");
var router = express.Router();
var sqlDo = require("../../js_help/DatabasReq/sqlDo.js");
router.get("/", async function(req, res){
var json = sqlDo.ExecCommand("select * from Users");
res.send(json); //json.recordset
});
module.exports = router;
In sqlDo.js:
module.exports = {
ExecCommand: function(command){
// sql and config are defined before.
sql.connect(config, function () {
var request = new sql.Request();
request.query(command, function (err, recordset) {
if (err) console.log(err)
console.log(recordset.recordset);
return recordset;
});
});
}
};
我的问题是这段代码正在异步运行。我试过将 await 放在不同的地方,但没有任何效果。所以当我启动我的服务器时,它什么都不返回。我可以说它正在完成呼叫,因为我让它将结果读入控制台。
谢谢你的帮助!
顺便说一句:我试过谷歌搜索/stackoverlow-ing,.. 但我找不到任何看起来像 C# 等效的东西。甚至可以像在 c# 中那样编写它吗?再次感谢您的每一个回答...
为了让你的ExecCommand
函数异步,你必须让它返回一个 Promise。例如在这里阅读 Promises
module.exports = {
ExecCommand: function(command){
return new Promise((resolve, reject) => { //return a Promise from the function
sql.connect(config, function () {
var request = new sql.Request();
request.query(command, function (err, recordset) {
if (err) {
reject(err); //if there is an error, reject the Promise
} else {
resolve(recordset); //if no error, resolve the Promise with the result
}
});
});
});
}
};
根据您的 SQL 库,它也可能已经支持承诺,而不是回调
module.exports = {
ExecCommand: function(command) {
return sql.connect(config)
.then(() => {
return new sql.Request().query(command);
})
}
};
或与 async/await
module.exports = {
ExecCommand: async function(command) {
await sql.connect(config);
return await new sql.Request().query(command);
}
};
然后你可以像这样在请求处理程序中调用这个函数
router.get("/", async function(req, res){
try {
var json = await sqlDo.ExecCommand("select * from Users");
res.send(json);
catch (err) {
console.log(err);
res.sendStatus(500);
}
});
或者像这样
router.get("/", function(req, res){
sqlDo.ExecCommand("select * from Users")
.then(json => { //the promise resolved
res.send(json);
})
.catch(err => { //the promise rejected
res.sendStatus(500);
console.log(err);
});
});
我更喜欢第二种变体。但这可能只是我个人的看法......
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句