无法从模块获取函数的返回值

时间:2019-06-06 16:47:59

标签: node.js express

从路由中我想调用属于模块的功能:

    const fs = require('fs');
    var path = require('path');
    var express = require('express');
    var async = require('async');
    var utils = require('./utils'); // this is the module
    var router = express.Router();
    var mysql = require('mysql');
    var connexion = mysql.createConnection({
                                                host: "localhost",
                                                user: "root",
                                                password: "root",
                                                database: "george"
                                            });

router.post('/insertAxes', function(req, res) {
    fs.readFile(path.join(__dirname, '../config/Bd_region_zone_juin19.geojson'), (err, data) => {
        if (err) throw err;
        let json = JSON.parse(data);
        var features = json.features;
        var axes = [];
        async.eachOf(features, function(item, position, cb) {
                                var featureJSON = features[position];
                                var propertyJSON = featureJSON.properties;
                                var axeLib = propertyJSON.Axes2019;
                                var regionId = utils.getRegionIdFromLib(propertyJSON.lib_rc);
                                var geometryJSON = featureJSON.geometry;
                                var coordinates = geometryJSON.coordinates;
                                var polygone = 'ST_GeomFromGeoJSON(\'{"type":"MultiPolygon", "coordinates":'+coordinates+'}\')';
                                axes.push([regionId]);
                                cb();
                            }, function() {
                                connexion.query("insert into axe(axe_libelle) values ?", [axes], (err, result) => {
                                    if (err) {
                                        throw err;
                                    }
                                });
                            });
        res.send(json);
    });
});

这里是模块:

var async = require('async');
var mysql = require('mysql');
var connexion = mysql.createConnection({
                                            host: "localhost",
                                            user: "root",
                                            password: "root",
                                            database: "george"
                                        });

/**
 * Permet de savoir si un élément est dans un tableau contenu dans un tableau
 * @param {array} tabData tableau de tableaux
 * @param {number} positionElement position de l'élément dans le second tableau
 */
exports.isDataInArrayOfArray = function (tabData, positionElement, element) {
    var tmp = [];
    async.eachOf(tabData, function(item, position, cb) {
        var dataArray = tabData[position];
        tmp.push(dataArray[positionElement]);
        cb();
    }, function() {});
    return tmp.includes(element);
};

/**
 * Permet de récupérer la clé primaire d'une région selon la région libellé
 * @param {string} regionLib Libellé de la région
 */
exports.getRegionIdFromLib = function (regionLib) {
    var ret = 0;
    connexion.query("select region_id from region where region_libelle = ? limit 1", [regionLib], (err, rows) => {
        if (err) {
            throw err;
        }
        ret = rows[0].region_id;
        console.log(ret);
    });
    return ret;
};

console.log显示值,但是到达var regionId = utils.getRegionIdFromLib(propertyJSON.lib_rc);时我得到0!那怎么了?

1 个答案:

答案 0 :(得分:1)

您对connexion.query的调用是异步的,因此getRegionIdFromLib函数在查询完成之前返回。

因此,您得到的初始值为0。

也许您可以接受回调函数,并在准备就绪时将其传递给regionId

exports.getRegionIdFromLib = function (regionLib, callback) {
  var ret = 0;
  connexion.query("select region_id from region where region_libelle = ? limit 1", [regionLib], (err, rows) => {
    if (err) {
      throw err;
    }
    ret = rows[0].region_id;
    console.log(ret);
    callback(ret);
  });
};

...然后:

async.eachOf(
  features,
  function(item, position, cb) {
    var featureJSON = features[position];
    var propertyJSON = featureJSON.properties;
    var axeLib = propertyJSON.Axes2019;
    var geometryJSON = featureJSON.geometry;
    var coordinates = geometryJSON.coordinates;
    var polygone = 'ST_GeomFromGeoJSON(\'{"type":"MultiPolygon", "coordinates":'+coordinates+'}\')';

    // Move "cb" call inside the callback
    utils.getRegionIdFromLib(propertyJSON.lib_rc, function(regionId) {
      axes.push([regionId]);
      cb();
    });
  },
  function() {
    connexion.query("insert into axe(axe_libelle) values ?", [axes], (err, result) => {
      if (err) {
        throw err;
      }
    });
  });

我希望这会有所帮助。