问题在于,在回调中,我尝试设置article.color
,但如果我在console.log(article.color)
之后添加color
,它仍然是#FF0000(在color
内部,它会检测到显性颜色和工作完美)。
如何在回调中更新变量?
var articles = JSON.parse( fs.readFileSync( 'src/articles/articles.json' , 'utf8') );
var totalArticles = articles.length;
var readyArticles = 0;
function testReady(){
readyArticles++;
if(readyArticles == totalArticles){
fs.writeFile('src/articles/articles.build.json', JSON.stringify(articles));
}
}
articles.forEach(function( article ) {
var imgPath = './src/'+article.background;
article.color = '#FF0000';
color( imgPath , function(err, color) {
if( !err ){
article.color = color;
} else {
console.log( err, color );
}
});
testReady()
});
答案 0 :(得分:0)
提示@CherryDT工作解决方案是:
var articles = JSON.parse(fs.readFileSync('src/articles/articles.json', 'utf8'));
var totalArticles = articles.length;
var readyArticles = 0;
function testReady() {
readyArticles++;
if (readyArticles == totalArticles) {
console.log('Add ' + readyArticles + ' colors');
fs.writeFile('src/articles/articles.build.json', JSON.stringify(articles));
}
}
articles.forEach(function(article) {
article.color = '#FF0000';
color('./src/' + article.background, function(err, color) {
if (!err) {
article.color = '#' + color;
} else {
console.log(err, color);
}
testReady();
})
});