My objective is to run my lambda function in NodeJS to retrieve the NoIP’s stored IP address with the hostname and username and password, using the “no-ip” nodejs library.
Here is my code: Sorry need to omit the hostname, user and pass value.
import NoIP from "no-ip";
async function noIPService() {
const noIP = new NoIP({
hostname: "",
user: "",
pass: ""
});
noIP.start();
noIP.on("success", (isChanged, ip) => { console.log("ip: ", ip); return ip; });
noIP.stop();
}
export const handler = async (event) => {
var result = await noIPService();
console.log("result: ", result);
}
I try to await for the success event. But somehow the lambda run through it without waiting for the success event to be triggered. So is there a way to listen to the success event before executing the rest of the code? Please advice
2
Your noIPService
function makes a call that will yield a result asynchronously but your code, as written, does not correctly wait for that asynchronous callback to happen.
One way to correct it is as follows, wrapping the asynchronous callback in a promise:
import NoIP from "no-ip";
async function noIPService() {
return new Promise((resolve, reject) => {
const noIP = new NoIP({
hostname: "xxx",
user: "yyy",
pass: "zzz"
});
noIP.start();
noIP.on("success", (isChanged, ip) => {
console.log("ip: ", ip);
noIP.stop();
resolve(ip);
});
noIP.on("error", (err) => {
console.log("error: ", err);
noIP.stop();
reject(err);
});
});
}
export const handler = async (event) => {
const result = await noIPService();
console.log("result: ", result);
}