'Async fetch with timeout for every request in loop

I have a list of domains. Need to get response status for all domains asynchronously. (but make a timeout for each request of 3 seconds, so that in case of a long answer, skip it and move on).

But the problem is that the timeout is triggered in general, not on every request and after 3 seconds all responses fail with a "timeout" error. Are there any options how to solve this issue?

import mysql from 'mysql2';
import 'dotenv/config';
import fetch from "node-fetch";

const connection = mysql.createConnection({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    database: process.env.DB_DATABASE,
    password: process.env.DB_PASSWORD
});

const sqlQuery = 'SELECT `domain` FROM `domains` LIMIT 1000';
connection.query(sqlQuery, function (error, results) {
    results.forEach(async(result) => {
        let domainName = 'https://' + result.domain;
        getDomain(domainName);
    });
});

function fetchPromise(url, options, timeout = 3000) {
    return Promise.race([
        fetch(url, options),
        new Promise((_, reject) =>
            setTimeout(() => reject(new Error('timeout')), timeout)
        )
    ]);
}

function getDomain(domain) {
    fetchPromise(domain, {
        method: 'get',
    }, 3000).then(resp => {
        console.log(domain + ' - ' + resp.status);
    }).catch(function (error) {
        console.log(domain + ' - ' + error.message);
    }); 
}

connection.end();


Solution 1:[1]

You can use much simpler like:

const arr = [1, 2, 3, 4, 5]
const reversedArr = []

for (let i = arr.length - 1; i >= 0; i--) {
  reversedArr.push(arr[i])
}

console.log(reversedArr)

Explanation is just, iterating over each item in the original array, but starting from the last item (arr.length = 5 here) and push each of them to a new array.

Solution 2:[2]

The code is just doing a reverse function.

The let temp = arr[i];arr[i] = arr[n-i];arr[n-i] = temp; is trying to switch the sequence between the i item and the i item from the last element,.

In your code, n is the last element.

Example, i =0, temp will equal to be the first element in arr which is 1, and arr[n-i] will be the last i element (the last element) which is 7.

Then, the code set arr[i] (first element in arr) to the last element value arr[n-i] which is 7.

Finally, the code assign the value of the arr[n-1] (last element in arr) to temp which is 1 and the first element in arr .

So you successfully reverse the first and last element and the loop keep doing the same thing when i=1,2......

let arr = [1, 2, 3, 4, 5, 6, 7];
let n = arr.length-1;

for(let i=0; i<=n/2; i++) {
  let temp = arr[i];
  arr[i] = arr[n-i];
  arr[n-i] = temp;
}
console.log(arr);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Do?ukan Akkaya
Solution 2 James