javascript - 如何让nodejs等待用其他javascript文件编写的函数完成
问题描述
我正在尝试在 nodejs 中使用 javascript 函数的结果,但是由于 nodejs 是异步的,它不会等待函数完成。关于如何让节点等待此功能完成的任何帮助都会很棒。
被调用的代码:
const patientId = function(patientUUID) {
var mysql = require('mysql');
var connectionF = mysql.createConnection({
host : 'localhost',
user : 'localuser',
password : 'localpass',
database: 'localdb'
});
connectionF.connect();
connectionF.query(patientIDFinderQuery, [patientUUID], function(error,result,fields) {
return result[0].patient_id; // I am trying to capture this result precisely
} );
}
调用代码:
app.post('/pushdata', function (req, res,next) {
connection.query(creatorQuery, [login], function(error,result,fields) {
let visit = req.body.visits[0]
let patientUUID = visit.patient
let patientId = dbHelper.patientId(patientUUID); // This is where the code is being called
console.log(patientId); // Returns Undefined
}
});
res.json({'status':'ok'})
})
解决方案
const patientId = function(patientUUID) {
return new Promise (resolve, reject => {
... more code
connectionF.query(patientIDFinderQuery, [patientUUID], function(error,result,fields) {
resolve(result[0].patient_id);
} );
});
}
...more code
dbHelper.patientId(patientUUID). then (patientId => {
console.log(patientId)
});
将 PatientId 方法设为 promise 函数。
推荐阅读
- java - 如何从十六进制转换为十进制以及从十进制转换为二进制
- c# - XAMLServices.Load 到接口
- python-3.x - GCP Cloud Functions 多线程发布请求
- javascript - Javascript模板渲染函数返回未定义
- header - HTTP IF MODIFIED SINCE SINCE 谷歌的页面标题
- c# - ResourceDictionary 内 ControlTemplate 中的按钮命令
- python - 在 Python 中读取和写入有效的 Json 文件输出
- html - 反应本机选择:访问键/所选选项的索引
- python - 一夜之间处理日期时间
- puppet - Puppet 查找找不到层次键值