如何在 Node.js 中完成 for 循环后运行函数

How could I run a function after the completion of a for loop in Node.js?

本文关键字:循环 for 运行 函数 Node js      更新时间:2023-09-26

假设我在 Node 中有一个结构.js如下所示:

for (i = 0; i < 50; i++) {
    //Doing a for loop.
}
function after_forloop() {
    //Doing a function.
}
after_forloop();

那么如何确保 forloop 完成后触发 after_forloop() 函数呢?

如果你想看看我实际在做什么:

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World'n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
var proxyChecker = require('proxy-checker');
var fs = require('fs');
function get_line(filename, line_no, callback) {
    fs.readFile(filename, function (err, data) {
        if (err) throw err;
        var lines = data.toString('utf-8').split("'n");
        var firstLineBreak = data.toString('utf-8').indexOf("'n");
        var originalText = data.toString('utf-8');
        var newText = originalText.substr(firstLineBreak + 1);
        if(+line_no > lines.length){
            return callback('File end reached without finding line', null);
        }
        callback(null, lines[+line_no], newText);
    });
}

for (i = 0; i < 50; i++) {
    get_line('proxy_full.txt', i, function(err, line, newText){
        fs.appendFile('proxy.txt', line + ''n', function (err) {
            if (err) throw err;         
        });     
        fs.writeFile('proxy_full.txt', newText, function (err) {
            if (err) throw err;
        });
    })
}
after_forloop();
function after_forloop() {
    proxyChecker.checkProxiesFromFile(
        // The path to the file containing proxies
        'proxy.txt',
        {
            // the complete URL to check the proxy
            url: 'http://google.com',   
            // an optional regex to check for the presence of some text on the page
            regex: /.*/
        },
        // Callback function to be called after the check
        function(host, port, ok, statusCode, err) {
            if (ok) {
                console.log(host + ':' + port);
                fs.appendFile('WorkingProxy.txt', host + ':' + port + ''n', function (err) {
                    if (err) throw err;             
                });
            }                   
        }
    );
    setTimeout(function(){
        fs.writeFile('proxy.txt', "", function (err) {
            if (err) throw err;
        });
        console.log('Proxy Check Completed.')
        process.exit(1); 
    }, 5000);
}

基本上,我喜欢允许节点服务器一次(在五秒内)在列表代理服务器上运行50个测试。然后服务器应将工作代理保存到新文件中。

也许这会有所帮助:

var operationsCompleted = 0;
function operation() {
    ++operationsCompleted;
    if (operationsCompleted === 100) after_forloop(); 
}
for (var i = 0; i < 50; i++) {
    get_line('proxy_full.txt', i, function(err, line, newText){
        fs.appendFile('proxy.txt', line + ''n', function (err) {
            if (err) throw err;
            operation();
        });     
        fs.writeFile('proxy_full.txt', newText, function (err) {
            if (err) throw err;
            operation();
        });
    })
}

诚然,这不是一个优雅的解决方案。如果你正在做很多这样的事情,你可能想看看像Async.js这样的东西。

如果你在 for 循环中执行任何异步操作,你可以简单地保持它

function after_forloop() {
// task you want to do after for loop finishes it's execution
}

 for (i = 0; i < 50; i++) {
 //Doing a for loop.
 if(i == 49) {
  after_forloop() // call the related function
 }
}

仍然在 node.js 中,您应该看到异步模块,而不是使用带有异步函数的 for 循环。这是异步.js或者您也可以考虑使用递归。

如果没有魔法发生,那么它应该是直截了当的。

功能:-

function after_forloop() {
    //Doing a function.
}

对于循环:-

for (i = 0; i < 50; i++) {
    //Doing a for loop.
}
for (i = 0; i < 50; i++) {
    //Doing another for loop.
}
after_forloop();

这将在两个循环完成后立即调用for after_forloop。由于for循环是阻塞调用,因此调用after_forloop()必须等待。

注意:- 如果您在for循环中执行一些async任务,则该函数将在循环完成后调用,但您在循环中执行的工作在调用函数时可能尚未完成。

您可以使用条件检查索引处理 for 循环的最后一次迭代。

for(let i = 0; i < 10; i++){
  if(i == 10 - 1){
    your_function();
  }
}

使用异步模块,它简单而最好。

async.each(array, function (element, callback) {
                        callback()
                    }, async function (err) {
                       console.log("array ends")
                    });

最简单的一个!

try {
  for (i = 0; i < 50; i++) {
    //Doing a for loop.
  }
} finally {
  after_forloop();
}