0

Here is a function to find mx records of a service and i need to save the one value(with the lowest priority) to make a request to it. How can I save and return this value?

const dns = require('dns');
const email = '...@gmail.com'
let res = email.split('@').pop();

function getMxRecords(domain) {
  return new Promise(function(resolve, reject) {
    dns.resolveMx(domain, function(err, addresses) {
      if (err) {
        //console.log(err, err.stack)
        resolve(null);
      } else {
        //console.log(addresses);
        let copy = [...addresses];
        //console.log(copy);
        let theone = copy.reduce((previous, current) => {
          if (previous.priority < current.priority) {
            return current;
          }
          return previous;
        });
        resolve(theone);
      }
    });
  });
}

let a = getMxRecords(res);
console.log(a);

Yeah, so i need to export this module to make a request to it like below;

let socket = net.createConnection(25, request(email), () => {})

so for this my function should request me or array or object with only one value, when i'm trying it doesn't work, i always get this: Promise { } //HERE IS RETURN FROM MY FUNCTION (WITH .THEN) Error in socket connect ECONNREFUSED 127.0.0.1:25

Cribe
  • 1
  • 1
  • 4
  • 1
    Does this answer your question? [Why is my asynchronous function returning Promise { } instead of a value?](https://stackoverflow.com/questions/38884522/why-is-my-asynchronous-function-returning-promise-pending-instead-of-a-val) – Ivar Aug 09 '22 at 14:36

1 Answers1

-1

A Promise is mostly an asynchronous call. It returns an Promise-Object that will resolve or reject the Promise. To access the result, you will call some functions:

function getMxRecords(domain) {
  return new Promise(function(resolve, reject) {
    dns.resolveMx(domain, function(err, addresses) {
      if (err) {
        //console.log(err, err.stack)
        resolve(null);
      } else {
        //console.log(addresses);
        let copy = [...addresses];
        //console.log(copy);
        let theone = copy.reduce((previous, current) => {
          if (previous.priority < current.priority) {
            return current;
          }
          return previous;
        });
        resolve(theone);
      }
    });
  });
}

getMxRecords(res)
  .then(yourResolveValueProvided => {
    // Your code if the promise succeeded
  })
  .catch(error => {
    // Your code if the promises reject() were called. error would be the provided parameter.
  })
IISkullsII
  • 705
  • 1
  • 7