Node js调用函数,该函数访问mysql数据库并多次返回json结果 [英] Node js call function, that access mysql database and returns json result, multiple times

查看:95
本文介绍了Node js调用函数,该函数访问mysql数据库并多次返回json结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node.js的新手.我有一个函数'getFromDb',该函数访问mysql数据库并返回带有一些数据的json文件.如果我有一个查询数据数组,并且想通过一个for循环调用相同的函数以获取数组中每个元素的json文件怎么办?

I'm new to Node.js. I have a function 'getFromDb' that accesses a mysql database and returns a json file with some data. What if I have an array of query data and I want to call the same function through a for loop to get a json file for each element of the array?

        var http = require('http');         

        http.createServer(function(req, res) {

            console.log('Receving request...');

            var callback = function(err, result) {
                res.setHeader('Content-disposition', 'attachment; filename=' + queryData+ '.json');
                res.writeHead(200, {
                    'Content-Type' : 'x-application/json'
                });
                console.log('json:', result);
                res.end(result);    
            };

        getFromDb(callback, queryData);}  
        ).listen(9999);

        function getFromDb(callback, queryData){
        var mysql = require('mysql');
            var connection = mysql.createConnection({
                host : 'localhost',
                user : 'xxxx',
                password : 'xxxx',
                database : 'xxxx',
                port: 3306
            });

            connection.connect();
            var json = '';
            var data = queryData + '%';
            var query = 'SELECT * FROM TABLE WHERE POSTCODE LIKE "' + data + '"';
            connection.query(query, function(err, results, fields) {
                if (err)
                    return callback(err, null);

                console.log('The query-result is: ', results);

                // wrap result-set as json
                json = JSON.stringify(results);

                /***************
                * Correction 2: Nest the callback correctly!
                ***************/
                connection.end();
                console.log('JSON-result:', json);
                callback(null, json);
            });
        }

推荐答案

您可以为此节点使用异步库.该库具有许多功能,这些功能使NodeJS中的异步编程变得更加容易. 每个"或每个系列"功能将起作用. 每个"将一次对mysql进行所有调用,而"eachSeries"将等待上一个调用完成.您可以在数组的getFromDB方法内使用它.

You could use the async library for node for this. That library has many functions that make asynchronous programming in NodeJS much easier. The "each" or "eachSeries" functions would work. "each" would make all the calls to mysql at once time, while "eachSeries" would wait for the previous call to finish. You could use that inside your getFromDB method for your array.

请参阅: https://github.com/caolan/async#each

var http = require('http'),
  async = require('async');

http.createServer(function(req, res) {

    console.log('Receving request...');

    var callback = function(err, result) {
      res.setHeader('Content-disposition', 'attachment; filename=' + queryData+ '.json');
      res.writeHead(200, {
        'Content-Type' : 'x-application/json'
      });
      console.log('json:', result);
      res.end(result);
    };

    getFromDb(callback, queryData);}
).listen(9999);

function getFromDb(callback, queryData){
  var mysql = require('mysql');
  var connection = mysql.createConnection({
    host : 'localhost',
    user : 'xxxx',
    password : 'xxxx',
    database : 'xxxx',
    port: 3306
  });

  connection.connect();

  var arrayOfQueryData = ["query1", "query2", "query3", "query4", "query5"];
  var jsonResults = [];

  async.each(arrayOfQueryData, function (queryData, cb) {
    var data = queryData + '%';
    var query = 'SELECT * FROM TABLE WHERE POSTCODE LIKE "' + data + '"';
    connection.query(query, function(err, results, fields) {
      if (err)
        return cb(err);
      console.log('The query-result is: ', results);
      // wrap result-set as json
      var json = JSON.stringify(results);
      console.log('JSON-result:', json);
      jsonResults.push(json);
      cb();
    });

  }, function (err) {
    connection.end();
    // callbacks from getFromDb
    if (err) {
      callback(err);
    }
    else {
      callback(null,jsonResults);
    }
  });
}

这篇关于Node js调用函数,该函数访问mysql数据库并多次返回json结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆