简体   繁体   English

在节点js中执行下一条语句之前等待回调完成

[英]Wait for callback to finish before executing next statement in node js

New to NodeJs. NodeJs 新手。 I am having an issue with synchronizing method execution.我在同步方法执行时遇到问题。 heres is what I mean, I have a controller which is responsible for: a.这就是我的意思,我有一个 controller 负责: Calling a method (in separate JS file) to open database connection and retrieve data.调用方法(在单独的 JS 文件中)打开数据库连接并检索数据。 b.湾。 It then sends the data to the front end.然后它将数据发送到前端。 From my debugging efforts it would appear I am sending the data before the method that opens the connection and gets the data completes.从我的调试工作来看,我似乎是在打开连接并获取数据的方法完成之前发送数据。 I know this because when the last line of salesController.js executes it gives error 'Cannot read property 'recordsets' of undefined'.我知道这一点,因为当 salesController.js 的最后一行执行时,它会给出错误“无法读取未定义的属性 'recordsets'”。 In following code snippet dbAccess.js has method that opens the db and gets data.在以下代码片段中,dbAccess.js 具有打开数据库并获取数据的方法。 salesController.js then sends that data. salesController.js 然后发送该数据。 Need help with the highlighted portion in salesController.js.需要有关 salesController.js 中突出显示部分的帮助。 Note if it helps I am using sql server as backend.请注意,如果它有助于我使用 sql 服务器作为后端。

dbAccess.js dbAccess.js

const dbConfig = require('../../nodeApp/dbConfig')

module.exports = {
    makeDBAccess: function(sqlString, req, res) {
        var sql = require("mssql/msnodesqlv8");
        // connect to your database
        sql.connect(dbConfig, function (err) {


            if (err) console.log(err);

            // create Request object
            var request = new sql.Request();

            // query to the database and get the records
            request.query(sqlString, function (err, recordset) {

                if (err) console.log(err)

                console.log(recordset.recordsets[0]);
                console.log(recordset.recordsets[0].length)

                return recordset;
            });
        });
    }
}

salesController.js salesController.js

const express = require('express');
var router = express.Router();
var dbAccess = require('../utility/dbAccess.js')
var utility = require('../utility/readfile.js')


router.get('/totalSales2011', function (req, res) {
    var sqlString = utility.readFileFunc("queries/sales2011.sql");
    var recordSet = dbAccess.makeDBAccess(sqlString,req,res); **//Get data from database**
    res.send(recordSet.recordsets[0]); **//Wait for line above to complete before doing this.**
});

module.exports = router;

cause in javascript functions returns undefined if you didn't add a return statement, the makeDBAccess function doesn't contain a return so it returns undefined .如果您没有添加return语句,javascript 函数中的原因将返回undefinedmakeDBAccess function 不包含 return 所以它返回undefined

As for what to do about this, you need to use callback or promises since connecting to your database and making a database query are both non-blocking asynchronous operations.至于如何处理,您需要使用回调承诺,因为连接到数据库和进行数据库查询都是非阻塞异步操作。

dbAccess.js dbAccess.js

const dbConfig = require('../../nodeApp/dbConfig')

module.exports = {
    makeDBAccess: function(sqlString, callback) {
        var sql = require("mssql/msnodesqlv8");
        // connect to your database
        sql.connect(dbConfig, function (err) {


            if (err) return callback(err);

            // create Request object
            var request = new sql.Request();

            // query to the database and get the records
            request.query(sqlString, function (err, recordset) {

                if (err) return callback(err)


                return callback(null, recordset);
            });
        });
    }
}

salesController.js salesController.js

const express = require('express');
var router = express.Router();
var dbAccess = require('../utility/dbAccess.js')
var utility = require('../utility/readfile.js')


router.get('/totalSales2011', function (req, res) {
    var sqlString = utility.readFileFunc("queries/sales2011.sql");
    var recordSet = dbAccess.makeDBAccess(sqlString, (err, recordSet) => {
          if (err) console.error(err);
          else res.send(recordSet.recordsets[0]);
    });

});

module.exports = router;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM