javascriptnode.jspromisemaxmind

Opening maxmind DB and accessing it in nodejs


Previously I was using like this:

Opening Maxmind db in Nodejs

Now, updated the modules as per node 10. So, need help to integrate it.

reference

const maxmind = require('maxmind');
exports.getIsoCountry = function(pIpAddress) {

  modules.debugLog('inside getIsoCountry : ',pIpAddress);

  maxmind.open(sGlAppVariable.maxmindDbPath)
  .then(function(lookup) {
    var ipData = lookup.get(pIpAddress);
    //console.log(ipData);
    console.log('iso_code',ipData.country.iso_code);
    return ipData.country.iso_code;
  });

}

console.log(getIsoCountry('66.6.44.4')); it should print country code. but it is undefined always. because this is a promise.

How to call this getIsoCountry function?

Any help will be appreciated.


Solution

  • You need to wait for execution to complete, for that, you should use Promise.

    Modify your code as below, then it should work:

    const maxmind = require('maxmind');
    exports.getIsoCountry = function(pIpAddress) {
      return new Promise((resolve, reject) => {
        modules.debugLog('inside getIsoCountry : ',pIpAddress);
          maxmind.open(sGlAppVariable.maxmindDbPath)
          .then(function(lookup) {
            var ipData = lookup.get(pIpAddress);
            console.log('iso_code',ipData.country.iso_code);
            resolve(ipData.country.iso_code);
          });
      });
    }
    
    getIsoCountry("66.6.44.4").then((rData) => {
      console.log(rData)
    });
    

    Below is sample code:

    var getIsoCountry = function(pIpAddress) {
    
      return maxmind().then(function() {
           return "Code for IP: " + pIpAddress;
        });
    
      function maxmind() {
        return new Promise((resolve, reject) => {
          resolve("done")
        });
      }
    
    }
    
    getIsoCountry("1.1.1.1").then((data) => {
      console.log(data)
    });