0

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)
})();
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Gary
  • 909
  • 9
  • 26
  • 1
    You can't just use `await` because `dns.reverse` doesn't return a promise - you need `new Promise` so you get `resolve` and `reject`. – jonrsharpe Dec 08 '20 at 21:55
  • Since you're asking about node.js, the proper approach is to use `util.promisify` here. But that just hides the `new Promise`, it doesn't remove it. The solution to your academic exercise is: `async`/`await` does not work without promises. It is built on promises, and it provides no syntactic sugar for promisification. – Bergi Dec 08 '20 at 22:01
  • I understand and thank you; I'd add though that this implementation does appear to add some syntactic sugar: async function f() { return 1; } f().then(alert); // 1 – Gary Dec 08 '20 at 22:10

0 Answers0