限制await dns反向函数js的执行时间

Limit execution time of await dns reverse function js

我有一个函数 A,它执行 dns.reverse(ip)(使用 'dns' js npm)来检查 IP 是否被使用。如果它抛出一个错误它是免费的。大多数 IP 都按预期工作,因为它会立即抛出错误,但问题是有些 IP 没有,它会等待 1.2 分钟超时。

var dns = require('dns')
async function A(ip){
try{
 var host = await dns.reverse(ip)
 if (host.length >1) //its used
}catch(e){
 // free ip if dns.reverse failed
}
}

我有没有办法将 await dns.reverse(ip) 的执行时间限制为 5 秒,这样它就不会等待整个 1.20 分钟,如果超过 5 分钟就抛出错误秒查找? 谢谢!

您可以这样使用 Promise.race()

const dns = require('dns');

const timeout = (delay, message) => new Promise((_, reject) => setTimeout(reject, delay, message));

const delay = 5000;

async function A(ip) {
    try {
        const host = await Promise.race([dns.reverse(ip), timeout(delay, `DNS resolution timed out after ${delay} ms`)]);
        console.log(host);
    } catch (e) {
        console.error(e);
    }
}

纯属娱乐:)可取消版本(中止相关网络请求)

import CPromise from "c-promise2";
import dns from 'dns';

const reverseIP = (ip, ms) => new CPromise((resolve, reject, {onCancel}) => {
    const resolver = new dns.Resolver();
    resolver.reverse(ip, (err, hosts)=> err? reject(err) : resolve(hosts));
    onCancel(() => resolver.cancel())
}).timeout(ms);

reverseIP('216.58.214.206', 2000)
    .then(hosts=> console.log(`Host: ${hosts}`), err=> console.warn(`Fail: ${err}`));

const request= reverseIP('16.58.214.206', 2000)
    .then(hosts=> console.log(`Host: ${hosts}`), err=> console.warn(`Fail: ${err}`));

setTimeout(()=> request.cancel(), 100);

reverseIP('16.58.214.206', 2000)
    .then(hosts=> console.log(`Host: ${hosts}`), err=> console.warn(`Fail: ${err}`));

输出:

Host: bud02s23-in-f206.1e100.net,bud02s23-in-f14.1e100.net
Fail: CanceledError: canceled
Fail: CanceledError: timeout

Process finished with exit code 0