NodeJS 是否可以比setInterval的最短时间更快地循环

7bsow1i6  于 2023-03-17  发布在  Node.js
关注(0)|答案(1)|浏览(105)

我有一个node js脚本,它发送https请求并循环通过文本文档中的一大串字符串列表。问题是,这需要很长时间才能在所有这些上执行。我希望能够更快地执行此任务。
这是密码

const request = require('request');
const fs = require('fs');
const ids = fs.readFileSync('./list.txt', 'utf-8').split('\n');

let count = 0;

let i = 0;
let a = () => {
    setInterval(() => {
        const id = ids[i].trim();
        request.get(`https://websitethingy.com/endpoint/${id}`, {
            headers: {
                "User-Agent": "Android/126021",
                "Authorization": "auth_token"
            },
            body: ``
        }, (err, res, body) => {
            if (!err && res.statusCode == 404) {
                console.log("not found", id);
            }
            console.log(body);
            count += 1;
            process.title = `[total requests: ${count}]`;
        });
        ++i;
        if(i === ids.length) i = 0;
    }, 1);
}
a();

它每毫秒循环一次整个列表,每秒执行大约900个请求,我似乎找不到更快的方法来执行这项任务。

v8wbuo2f

v8wbuo2f1#

您可以使用.forEach循环更快地执行循环。

Node.js

const request = require('request');
const fs = require('fs');
let ids = fs.readFileSync('./list.txt', 'utf-8').split('\n');

let count = 0;

ids.forEach((id, i) => {
    request.get(`https://websitethingy.com/endpoint/${id.trim()}`, {
        headers: {
            "User-Agent": "Android/126021",
            "Authorization": "auth_token"
        },
        body: ``
    }, (err, res, body) => {
        if (!err && res.statusCode == 404) {
            console.log("not found", id);
        }
        console.log(body);
        count += 1;
        // process.title = `[total requests: ${count}]`;
        console.log(`[total requests: ${count}]`);
    });
});

香草精JS

let count = 0;
let ids = [...Array(20).keys()].slice(1); // [0, 1, ..., 19]
ids.forEach((id) => {
    fetch(`https://dummyjson.com/products/${id}`)
    .then((response) => response.json())
    .then((body) => {
        console.log(body);
        count++;
        console.log(`[total requests: ${count}]`);
    })
    .catch((err) => {
        console.log("not found", id);
        console.error(err);
    });
});

相关问题