Search code examples
javascriptreverse-dns

Limit execution time of await dns reverse function js


I have a function A that performs a dns.reverse(ip) (using 'dns' js npm) to check if IP is used or not. If it throws an error its free. Most of IPs it works as expected as it throws error straight away, but problem is that some IPs do not, it waits for 1.2minutes to timeout.

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
}
}

Is there a way for me to limit execution time of the await dns.reverse(ip) to lets say 5seconds, so it doesnt wait the whole 1.20min and just throw an error if it takes longer than 5 seconds to lookup? Thanks!


Solution

  • You can use Promise.race() like this:

    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);
        }
    }