在Node.js中完成for循环后,我怎么能运行一个函数?

时间:2015-01-13 02:49:47

标签: javascript node.js

假设我在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个测试(在五秒内)。然后服务器应该将工作代理保存到新文件中。

5 个答案:

答案 0 :(得分:5)

也许这会有所帮助:

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之类的内容。

答案 1 :(得分:3)

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

功能: -

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

For Loop: -

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

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

注意: - 如果您在async循环中执行了一些for任务,那么在循环结束后将调用该函数,但您在循环中执行的工作可能会在调用函数时没有完成。

答案 2 :(得分:3)

如果你在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循环。在这里Async.js或者您也可以考虑使用递归。

答案 3 :(得分:2)

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

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

答案 4 :(得分:0)

使用Async模块,它简单又好。

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