The following code makes use of a simple promise and works perfectly.
ipToDomain = (ip) => {
return new Promise((resolve, reject) => {
dns.reverse(ip, (err, domain) => {
if (err) {
reject(`ERROR: ${err.message}`)
} else {
resolve(domain);
}
});
})
}
I'd like to convert this into the same function using async and removing the promise. It's my understanding that using async will wrap my function in a promise. This is just an academic exercise to fully understand how async works.
See here, which is from URL https://javascript.info/async-await:
Async functions
Let’s start with the async keyword. It can be placed before a function, like this:
async function f() { return 1; }
The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically.
For instance, this function returns a resolved promise with the result of 1; let’s test it:
async function f() { return 1; } f().then(alert); // 1
…We could explicitly return a promise, which would be the same:
async function f() { return Promise.resolve(1); } f().then(alert); // 1
Unfortunately I can't get this function to work when I use async and forgo promises.
This doesn't work, but it outlines what I'm trying to do:
ipToDomain = async (ip) => {
return dns.reverse(ip, (err, domain) => {
if (err) {
reject(`ERROR: ${err.message}`)
} else {
resolve(domain);
}
});
})
}
(async () => {
const result = await ipToDomain('1.2.3.4');
console.log(result)
})();