【发布时间】:2021-08-24 11:26:47
【问题描述】:
如果我在 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 个测试(在五秒内)。然后服务器应该将工作代理保存到一个新文件中。
【问题讨论】:
-
循环后执行?注意你忘了声明
i。 -
“在
for循环完成之后”您可能的意思是“在for循环中启动的所有异步活动都完成之后”,对吧? -
这里没有什么特别之处,在
for循环结束后调用。 -
代码通常自上而下运行,但如果不是,您可以确保 i 为 50...
-
可以显示
for循环的内容吗?
标签: javascript node.js