循环中的每个请求都会随及时提取异步
我有一个域名。需要异步获得所有域的响应状态。 (但要对每个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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论