Wait On Event listener complete in a loop

70 Views Asked by At

I use a node package 'dnsbl-lookup' to check blacklist domains.

However, when I pass an array of domains to 'dnsbl-lookup' for checking, 'dnsbl-lookup' on events not waiting all Eventlistener complete, instead it return empty array.

How can I let all items get checked complete then return resultsArr array.

const lookup = require("dnsbl-lookup");

    const checkDomainsBlacklist = async (req, res, next) => {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return next(new HttpError("Invalid domain list", 422));
      }
    
      const { domains} = req.body;
      let resultsArr = [];

      for (let index = 0; index < domains.length; index++) {
        const domain= domains[index].trim();
        let checkCount = 0;
        let dnsbl = new lookup.dnsbl(domain, blockLists); 
        //`blockLists` => list of sites to validate domain blacklist

        dnsbl.on("error", function (error, blocklist) {
          console.log(error);
        });
    
        dnsbl.on("data", function (result, blocklist) {
          checkCount++;
          console.log(result.status + " in " + blocklist.zone);
    
          if (result.status === "listed") {
            let result = {
              url: domain,
              blUrl: blocklist.zone,
            };
            resultsArr.push(result);
          }
        });
    
        dnsbl.on("done", function () {
          console.log("lookup finished");
        });
      }
    
      res.status(202).json({ resultsArr: resultsArr });
    };
0

There are 0 best solutions below