首页 > 解决方案 > 如何让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'})
  })

标签: javascriptnode.js

解决方案


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 函数。


推荐阅读