javascript - C# 异步任务与 Js 异步任务(节点 js)
问题描述
好的,所以我知道如何用 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 库,它也可能已经支持 Promise,而不是回调
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);
});
});
我更喜欢第二种变体。但这可能只是我个人的看法......
推荐阅读
- javascript - react-vega - 如何添加下拉菜单以在没有 vega-embed 的情况下将应用程序反应到图表?
- outlook-addin - 获取 Office.context.mailbox.item for Outlook 中的所有可用值
- kubernetes - 处于“未就绪”状态的 kubernetes 工作节点
- reactjs - Reactjs Redux 登录/注册警报
- sql - 如何在保存到 OneDrive 的 Excel 工作簿中运行 SQL 查询?
- javascript - 为什么鼠标单击成功时 TWebbrowser IHTMLElement.click 失败
- php - WordPress:覆盖过滤器变量不起作用
- node.js - 在没有文件输入的情况下以 formData 发送图像
- git - git push 错误:错误:src refspec
不匹配任何 - memory - 计算页表参数的大小