Last active
October 13, 2017 23:15
-
-
Save javanigus/e28ca6ac8d50ba6ec516c191f6cec002 to your computer and use it in GitHub Desktop.
Nested JavaScript Loops Containing Async Functions That are Forced to Run Synchronously
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var translate = require('google-translate-api'); | |
var fs = require('fs'); | |
var async = require('async'); | |
// array of filenames | |
// each file contains a JSON object | |
var filenames = [ | |
"0001-school-life-buying-textbooks.js", | |
"0002-school-life-class-registration.js", | |
"0003-school-life-too-many-full-classes.js" | |
] | |
// loop over each filename and process asynchronously | |
async.eachSeries(filenames, function(filename, callback) { | |
// read each file synchronously and parse it into an object | |
var obj = JSON.parse(fs.readFileSync('dialogues/'+filename, 'utf8')); | |
var array1 = []; | |
// loop over each sentence and process asynchronously | |
async.eachSeries(obj.sentences, function(sentence, callback) { | |
// create an object to store the English and Indonesian sentence, e.g. | |
/*{ | |
"English": "How are you", | |
"Indonesian": "Apa kabar" | |
}*/ | |
var translatedSentence = {}; | |
translatedSentence["English"] = sentence.English; | |
// call translate function to translate English sentence into Indonesian | |
// even though translate function is async, this loop will run synchronously | |
translate(sentence.English, {from: 'en', to: 'id'}).then(res => { | |
translatedSentence["Indonesian"] = res.text; | |
array1.push(translatedSentence); | |
callback(); | |
}).catch(err => { | |
console.error(err); | |
callback(); | |
}); | |
}, function(err) { | |
// if any of the file processing produced an error, err would equal that error | |
if( err ) { | |
// One of the iterations produced an error. | |
// All processing will now stop. | |
console.log('A sentence failed to process'); | |
} else { | |
// write the array of translated sentence objects to file synchronously | |
var stream = fs.createWriteStream("indonesian/"+filename); | |
stream.once('open', function(fd) { | |
stream.write(JSON.stringify(array1, null, '\t')+"\n"); | |
stream.end(); | |
}); | |
console.log('All sentences have been processed successfully'); | |
} | |
}); | |
callback(); | |
}, function(err) { | |
if( err ) { | |
// One of the iterations produced an error. | |
// All processing will now stop. | |
console.log('A sentence failed to process'); | |
} else { | |
console.log('All sentences have been processed successfully'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment