Javascript 在 Node.js 中完成 for 循环后如何运行函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27914209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How could I run a function after the completion of a for loop in Node.js?
提问by Aero Wang
Say if I have a structure in Node.js shown below:
假设我在 Node.js 中有一个如下所示的结构:
for (i = 0; i < 50; i++) {
//Doing a for loop.
}
function after_forloop() {
//Doing a function.
}
after_forloop();
So how could I make sure the after_forloop() function is fired after the forloop is completed?
那么如何确保在 forloop 完成后触发 after_forloop() 函数呢?
In case if you want to see what I am actually working on:
如果你想看看我实际在做什么:
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);
}
Basically I like to allow the node server run 50 test on a list proxy servers at a time (within five seconds). And then the server should save the working proxies to a new file.
基本上我喜欢允许节点服务器一次(在五秒内)在列表代理服务器上运行 50 个测试。然后服务器应该将工作代理保存到一个新文件中。
回答by Ethan Lynn
Maybe this helps:
也许这有帮助:
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();
});
})
}
Admittedly this isn't an elegant solution. If you're doing a whole lot of this you might want to check out something like Async.js.
回答by Parth Vyas
If you're doing any async operation in the for loop, you can simply keep it like
如果你在 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
}
}
Still in node.js, instead of making use of for loops with asynchronous functions, you should see the async module. Here's Async.jsor you can consider using recursion too.
仍然在 node.js 中,而不是使用带有异步函数的 for 循环,您应该看到 async 模块。这是Async.js或者你也可以考虑使用递归。
回答by Mritunjay
If there is no magic happening then it should be straight forword.
如果没有魔法发生,那么它应该是直截了当的。
Function:-
功能:-
function after_forloop() {
//Doing a function.
}
For Loop:-
For循环:-
for (i = 0; i < 50; i++) {
//Doing a for loop.
}
for (i = 0; i < 50; i++) {
//Doing another for loop.
}
after_forloop();
This will call after_forloopjust after both forloops finishes. Because forloop is a blocking call, calling of after_forloop()has to wait.
这将after_forloop在两个for循环完成后立即调用。因为forloop 是一个阻塞调用,所以调用 ofafter_forloop()必须等待。
Note:-If you are doing some asynctask in forloops then the function will be called after loop finished, but the work you are doing in loops might not finished by the time of calling function.
注意:-如果您async在for循环中执行某些任务,则该函数将在循环完成后被调用,但您在循环中所做的工作可能在调用函数时尚未完成。
回答by Amit Rana
use the Async module, Its easy and best.
使用 Async 模块,它简单且最好。
async.each(array, function (element, callback) {
callback()
}, async function (err) {
console.log("array ends")
});
回答by Smit Luvani
for(var i=0; i < 100; i++){
//Write Your Program
if(i == 100-1){
//Write Your Code or Function
your_function()
}

