[英]Global Scope not working?
I'm currently trying to add the data from each JSON file in a specific folder to a string and then log that string to the console - but it's not working. 我目前正在尝试将特定文件夹中每个JSON文件中的数据添加到字符串中,然后将该字符串记录到控制台中-但它不起作用。 Is anyone able to shed some light on where I'm going wrong?
有人能阐明我要去哪里了吗?
global.article = "";
for(i=0;i<posts.length;i++){
fs.readFile('posts/' + posts[i], 'utf8', function(err, json){
var post = JSON.parse(json);
article += "<article>";
article += "<blockquote>";
article += "<h3>" + post.title + "</h3>";
article += "<small>" + post.date + "</small>";
article += post.content;
article += "</blockquote>";
article += "</article>";
});
}
console.log(article);
Instead of 'global.article', you should instead declare a new variable for the article. 代替“ global.article”,您应该为文章声明一个新变量。
var article = "";
If you need to update global.article when you have finished constructing the string in the loop, you can assign back to it when the loop exits. 如果在循环中构造完字符串后需要更新global.article,则可以在循环退出时将其分配回去。
global.article = article;
If for some reason you want to update global.article directly, you can update global.article instead, as shown in this JSFiddle: 如果出于某种原因要直接更新global.article,则可以改为更新global.article,如以下JSFiddle所示:
http://jsfiddle.net/Lkpe4/ http://jsfiddle.net/Lkpe4/
HTH HTH
fs.readFile
is asynchronous, so the console.log(article);
fs.readFile
是异步的,因此console.log(article);
at the bottom is going to run before any of your fs.readFile
callbacks with the JSON processing that populates article
. 最底部的代码将在您的任何
fs.readFile
回调之前运行,该回调具有填充article
的JSON处理。
Take a look at using the async
library to provide asynchronous flow control, but a simple solution that illustrates that nature of the problem is to keep track of the callback count and only process article
once they've all completed: 让我们看一下使用
async
库提供异步流控制,但是一个说明问题本质的简单解决方案是跟踪回调计数,并且仅在完成后才处理article
:
global.article = "";
var count = 0;
for(i=0;i<posts.length;i++){
fs.readFile('posts/' + posts[i], 'utf8', function(err, json){
var post = JSON.parse(json);
article += "<article>";
article += "<blockquote>";
article += "<h3>" + post.title + "</h3>";
article += "<small>" + post.date + "</small>";
article += post.content;
article += "</blockquote>";
article += "</article>";
if (++count === posts.length) {
// All callbacks are now complete.
console.log(article);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.