Opening maxmind DB and accessing it in nodejs - javascript

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.

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)
});

Related

How to wait for the end of the function

I have some task.
I'm creating my library which has a connection function written in it (several processes are included) and a creation function.
Need to clarify. The library doesn't deal with any http/https requests. Everything happens locally and without server requests.
Code from the testing side of the library
module.exports = async function connect(argument) {
const { save, models } = argument;
var prom = new Promise((resolve, reject) => {
setTimeout(() => {
checkDir(models);
// check models
checkBaseModels(models);
checkModels(models);
resolve();
});
});
prom.then(() => {
return new Promise((resolve, reject) => {
setTimeout(() => {
loadModels();
resolve();
}, 2000);
});
}).then(() => {
setTimeout(() => {
saveModels(save);
models_list();
});
});
};
const cloud = require('cloud');
const cloud = cloud.connect({ save: 1000 });
const create = cloud.create({
name: "Test",
description: "Abc"
});
What can be used to make other processes stop while the connection in my library is running.
I need to somehow fix this problem without using setTimeout and so on in the test. It is desirable to leave this code as it is.
I need to connect first, and then create.
The code on the test side, if possible, should preferably not be edited.
connect function is not returning the promise
module.exports.connect = async function connect(argument) {
// ...
return prom;
}
Connection file
(async () => {
const cloud = await cloud.connect({ save: 1000 });
const create = cloud.create({
name: "Test",
description: "Abc",
});
})();

How can I write promise chain

I have some Promises:
getJson = new Promise((resolve, reject) => {
$.getJSON(abiJson)
.done(abi => {
resolve(abi);
})
.fail(() => {
reject('Eror loading ABI '+name);
});
});
initWeb3 = () => {
return new Promise((resolve, reject) => {
(typeof web3 !== 'undefined') ?
resolve(new Web3(web3.currentProvider)):
reject('No find wallet, or web3 is undefined!');
});
}
initContract = () => {
return new Promise((resolve) => {
resolve(web3.eth.contract(abi).at(address));
});
}
initWallet = () => {
return new Promise((resolve, reject) => {
(window.web3.currentProvider.isMetaMask) ? resolve('Metamask') :
(window.web3.currentProvider.isTrust) ? resolve('Trust') :
(window.web3.currentProvider.constructor.name === 'EthereumProvider') ? resolve('Mist') :
(window.web3.currentProvider.constructor.name === 'Web3FrameProvider') ? resolve('Parity') :
reject('Not suported wallet');
});
}
initAccount = () => {
return new Promise((resolve, reject) => {
(typeof web3.eth.accounts[0] !== 'undefined') ?
resolve(web3.eth.accounts[0]) :
reject('Please login to the wallet');
});
}
Help me to write promise chain correctly.
First of all I need to getJson and write resolve to some var
Then i need initWeb3() and write resolve to some var
Then initContract(), but I need get abi from getJson and send it to initContract() and write resolve to some var
Then initWallet() and write resolve to some var
And initAccount() and write resolve to some var
Help me to write promise chain correctly, and tell me please this is good code or 'shitcode'?
In your case you can just use then() as you don't seem you do blocking tasks except for the first ajax request at the beginning.
So you can do it straight forward like this:
getJson()
.then(abi => {
initWeb3();
return abi;
})
.then(abi => {
initContract();
return abi;
})
.then(abi => {
initWallet();
return abi;
})
.then(initAccount) // you will find abi as the function argument
.catch(e => console.error('something goes wrong', e));
Don't forget to use the catch() method at the end of the chin in order to get any exception that can raise in the middle of your calls.
That way is fragile, as if something bad appened in one of the call, all others will be not executed.
And even debugging can be a nightmare.
I think looking yo your code, you can do it better this way:
getJson()
.then(abi => { // here you have the result
try {
initWeb3();
initContract();
initWallet();
initAccount();
} catch(e) {
// do something here
}
})
.catch(e => console.error('something goes wrong', e));
As anything seems to be dependant of initWeb3 you should put all in a try catch.
In that way you have the promise failing for the ajax call only, and when suceded you just execute yous stuff.
If you have an error in this last part, you have e better way to handle this.
In this way you can use the abi returned by the ajax call.

JavaScript | Access the object of a Promise from another Promise

In my AngularJS Application, I want to access the return value of a Promise, which I access from a service outside of my controller and import it there. This Promise, return an object. I want to access that objects and properties inside it.
I created the service to get that endpoint. Look below:
export const getEndpoints = () => {
const options = {
method: httpMethod.GET,
url: endpoint.ENVIRONMENT,
};
return Instance(options);
};
The above service in return reads an endpoint which I provide and uses axios on the background. This part is working just fine.
Then imported it, on my angular Controller:
import { getEndpoints } from './config/service';
Finally I created this function:
$scope.isItAvailable = false; // I will use this later to check the actual value. It is not important in the scope of the question..
const checkIfItIsAvailable = () => {
return new Promise((resolve, reject) => {
resolve(getEndpoints)
console.log(getEndpoints)
})
}
// And in my main function I am just calling the above
const mainFn = () => {
checkIfItIsAvailable()
// Along with a few others..
}
Actual Results
Now, in my console, I get the functioncheckIfItAvailable printed out.
Expected Results
I instead want to print to the console, the actual value that is being returned by the original promise, the object, and its properties.
Probably You need to call that function instead of just passing it as a parameter.
const checkIfItIsAvailable = () => {
return new Promise((resolve, reject) => {
resolve(getEndpoints()) // here
console.log(getEndpoints())
})
}
Then to get that resolved later in your main function, or wherever - just use then:
const mainFn = () => {
checkIfItIsAvailable().then((result) => {
// do what you need with result here
// $scope.isItAvailable = result probably like this
});
}
Please comment if you need another result. I see at least this issue at the moment.
Also, here is a snipper, illustrating that you need to call it instead of just passing.
// here is an example function which just return some string
function getSomething() {
return 'something'; // it could be a promise also
}
// here is example without calling functions, but just passing:
const promise = new Promise((resolve, reject) => {
console.log('NO CALL: ', getSomething);
});
// here is example with calling, so value is resolved
const promise2 = new Promise((resolve, reject) => {
console.log('CALLED: ', getSomething());
});
Here, getEndpoints is an asynchronous function which returns a Promise, and the way to get a return value from promise is to use then callback. You can do it like this:
const checkIfItIsAvailable = () => {
return new Promise((resolve, reject) => {
getEndpoints().then(resultOfEndPoint => {
console.log(resultOfEndPoint);
resolve(resultOfEndPoint);
});
})
}
It's possible to access the resolved result of getEndpoints in checkIfItIsAvailable calling getEndpoints() and using then() function:
const checkIfItIsAvailable = () => {
return new Promise((resolve, reject) => {
// call getEndpoints
getEndpoints()
// call then to get a result from getEndpoints
.then(res => {
console.log(res);
// checkIfItIsAvailable will be resolved with
// the result of getEndpoints
resolve(res);
});
});
}

return promise if download to the db is finished

hi I have such a code:
export const apiAddTodo = async (todoName, todoDesription, picture) => {
const todo = {
name: todoName,
body: todoDesription,
status: false
};
if (picture) {
const snapshot = await images(new Date().getTime()).put(picture);
todo.image = snapshot.metadata.downloadURLs;
}
return db.push(todo);
};
this code work with async/await but I want to rewrite it to the promise based just for the leaning purposes. In the if statemnt I need to wait for the image loading and after that proceed to the db.push method. Can somebody help me with that?
I tried such a code but it won't help me:
if (picture) {
return new Promise( res => {
images(new Date().getTime()).put(picture).then( snapshot => {
todo.image = snapshot.metadata.downloadURLs;
res(todo);
});
)}
}
The only difference is that, you are not pushing todo to db. The rest
looks good.
if (picture) {
return new Promise( res => {
images(new Date().getTime()).put(picture).then( snapshot => {
todo.image = snapshot.metadata.downloadURLs;
db.push(todo)
res(todo);
});
)}
}

how to make an async call to firebase?

I'm struggling to retrieve data from firebase. basically im creating a dating app and when a user "likes" someone, it should check the displayed users liked people array to see if the current user is in there and then "match" them if they are
I have this function:
pullFromFirebase = (displayedUser) => {
return new Promise((resolve, reject) => {
firebase.database().ref('users/' + displayedUser.id + '/usersLiked/').once('value').then(function(snapshot) {
const users = Object.keys(snapshot.val()).map(function(key) {
return snapshot.val()[key];
})
});
})
}
This function is working, coz when I console.log(users), I get the array of the people who are liked. however, when I call this function like so
async checkForMatch (currentUser, displayedUser) {
const likedUsers = await this.pullFromFirebase(displayedUser);
console.log(likedUsers, 'likedUsers');
}
nothing is being logged in the console? and when I take away the async stuff, the console.log just says it's pending. what have i done wrong or why cant i get the users displayed in my checkformatch function?
you never resolved your promise in pullFromFirebase method
checkout the code
pullFromFirebase = (displayedUser) =>
{
return new Promise((resolve, reject) =>
{
firebase.database().ref('users/' + displayedUser.id + '/usersLiked/').once('value').then(function (snapshot)
{
const users = Object.keys(snapshot.val()).map(function (key) {
return snapshot.val()[key];
})
resolve(users); // <--- here is the fix
});
})
}
You may have added a Promise there unnecessairily and your function returns a Promise which never resolves. firebase.database returns a Promise already but you also need to return the users you get within .then():
pullFromFirebase = (displayedUser) => {
return firebase.database().ref('users/' + displayedUser.id + '/usersLiked/').once('value').then(function(snapshot) {
const users = Object.keys(snapshot.val()).map(function(key) {
return snapshot.val()[key];
});
return users;
});
}
Or alternately, if you need that wrapping Promise you need to resolve it with the return value:
pullFromFirebase = (displayedUser) => {
return new Promise((resolve, reject) => {
firebase.database().ref('users/' + displayedUser.id + '/usersLiked/').once('value').then(function(snapshot) {
const users = Object.keys(snapshot.val()).map(function(key) {
return snapshot.val()[key];
})
resolve(users);
});
})
}

Categories

Resources