如何按顺序查询我的列表内容?

How do I query the contents of my list in order?

我正在尝试创建 DNS api。由于我的记录在节点js上是异步的,所以我无法匹配记录名称和记录值。我怎样才能同步这个构建?或者如何在记录值旁边添加记录名称?

import dns  from 'dns';

const rrtype="*";
const obj= ["A","MX","CNAME","NS","TXT"];
var myobj = [];


export const getAllRecords = (req,res) => {
    const {domain} = req.params;
    
        for(var i=0;i<obj.length;i++){
           dns.resolve(domain, obj[i], (err, records) => myobj.push(records));
        }
        setTimeout(function(){ 
        res.send(myobj);
        }, 1000);
        myobj = [];
        
}

您可以像@Barmar 建议的那样使用 Promise.All,或者如果您想按顺序进行 dns 查找,您可以这样做,请注意 dns.promises.resolve 的使用,其中 returns承诺而不是回调,并使用 async/await。我将它作为脚本进行了测试,所以我还将调用的输出放入 getAllRecords({ params: { domain: "gmail.com" } });


import dns from "dns";

const rrtype = "*";
const obj = ["A", "MX", "CNAME", "NS", "TXT"];

export const getAllRecords = async (req, res) => {
  const { domain } = req.params;

  let myObj = [];

  for (let i = 0; i < obj.length; i++) {
    try {
      const res = await dns.promises.resolve(domain, obj[i]);
      myObj.push({ recordType: obj[i], recordValue: res });
    } catch (err) {
      console.log(err);
    }
  }

  // Debug results
  console.log(JSON.stringify(myObj, null, 4));

  setTimeout(() => {
    // res.send(myObj);
    console.log(" === END ===");
  }, 1000);
};

// Simple test
getAllRecords({ params: { domain: "gmail.com" } });

输出:

> node dnsTest.js

Error calling resolve Error: queryCname ENODATA gmail.com
    at QueryReqWrap.onresolve [as oncomplete] (internal/dns/promises.js:170:17) {
  errno: 'ENODATA',
  code: 'ENODATA',
  syscall: 'queryCname',
  hostname: 'gmail.com'
}
[
    {
        "recordType": "A",
        "recordValue": [
            "142.250.184.5"
        ]
    },
    {
        "recordType": "MX",
        "recordValue": [
            {
                "exchange": "alt4.gmail-smtp-in.l.google.com",
                "priority": 40
            },
            {
                "exchange": "alt2.gmail-smtp-in.l.google.com",
                "priority": 20
            },
            {
                "exchange": "alt3.gmail-smtp-in.l.google.com",
                "priority": 30
            },
            {
                "exchange": "gmail-smtp-in.l.google.com",
                "priority": 5
            },
            {
                "exchange": "alt1.gmail-smtp-in.l.google.com",
                "priority": 10
            }
        ]
    },
    {
        "recordType": "NS",
        "recordValue": [
            "ns1.google.com",
            "ns3.google.com",
            "ns2.google.com",
            "ns4.google.com"
        ]
    },
    {
        "recordType": "TXT",
        "recordValue": [
            [
                "globalsign-smime-dv=CDYX+XFHUw2wml6/Gb8+59BsH31KzUr6c1l2BPvqKX8="
            ],
            [
                "v=spf1 redirect=_spf.google.com"
            ]
        ]
    }
]
 === END ===