0

I have an express endpoint that does a number of things, 1 of which is checking domain names availability against GoDaddy's API. I am not understanding how I can go about awaiting the results.

The loop will iterate my tlds array and check the domain name availability for each of them. Currently axios will return a promise from checkDomainAvailability, resolve, and push the data to the domains array (I'm certain this can be written better, but I'm not well versed in JS).

app.post("/domains", async (req, res) => {
  var brand = req.body.brand;
  let domains = [];

  // check domain availability
  const tlds = ["dev", "com", "tv", "io", "app", "me"];
  tlds.forEach(tld => {
    let domain = `${brand}.${tld}`;
    godaddy.checkDomainAvailability(domain).then(data => {
      domains.push(data);
    });
  });

res.send(domains);
}

godaddy.checkDomainAvailability()

const checkDomainAvailability = function(domain) {
  return api
    .get("/domains/available", {
      params: {
        domain: domain,
        checkType: "FULL",
        forTransfer: false
      }
    })
    .then(res => {
      return res.data;
    })
    .catch(err => {
      logger.error("Godaddy", err);
    });
};

The current result is obviously that express sends the result of domains before each has been iterated. How can I make this await the forEach loop?

I have attempted using for await as follows but seeing the same results.

  // check domain availability
  const tlds = ["dev", "com", "tv", "io", "app", "me"];
  for await (let tld of tlds) {
    let domain = `${brand}.${tld}`;
    godaddy.checkDomainAvailability(domain).then(data => {
      domains.push(data);
    });
  }
CodeSpent
  • 1,684
  • 4
  • 23
  • 46
  • 1
    You may want to try [`for await...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) or [`Bluebird Promise.reduce`](http://bluebirdjs.com/docs/api/promise.reduce.html) – gabriel.hayes Jan 22 '20 at 20:24
  • Have a look at this question and answer, I think it will help point you in the right direction. https://stackoverflow.com/questions/31413749/node-js-promise-all-and-foreach – Cal Irvine Jan 22 '20 at 20:28
  • @user1538301 I did try this with `for await` and still seeing the same results. I'll edit with my attempt. – CodeSpent Jan 22 '20 at 20:31

1 Answers1

2

The simplest solution here would be to encapsulate the loop logic inside another (async) function, and then await that function's result in your main set of code. For example:

app.post("/domains", async (req, res) => {
  var brand = req.body.brand;

  // check domain availability
  const tlds = ["dev", "com", "tv", "io", "app", "me"];
  let domains = await checkTLDs(tlds, brand);

  res.send(domains);
}

Here, checkTLDs() is an async function that handles the looping. Then, your main code can wait for it to finish before it does the res.send().

Sam Forbis
  • 179
  • 7