循环中的每个请求都会随及时提取异步

发布于 2025-01-30 08:04:42 字数 1204 浏览 0 评论 0原文

我有一个域名。需要异步获得所有域的响应状态。 (但要对每个3秒钟的请求进行超时,以便在长时间的答案中,跳过并继续前进)。

但是问题在于,超时是一般触发的,不是在每个请求上触发,3秒钟后,所有响应都以“超时”错误失败。有什么选择如何解决此问题?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文